Thursday, June 7, 2018

@Inject()

You can write this

import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'example-component',
  template: '
I am a component
'

})
class ExampleComponent {
  constructor(@Inject(Http) private http) {
    // use `this.http` which is the Http provider
  }
}
At this point, @Inject is a manual way of specifying this lookup token, followed by the lowercase http argument to tell Angular what to assign it against.

This could (and will) get very messy when a component or service requires a lot of dependencies. As Angular supports resolving dependencies from the emitted metadata, there’s no need to use @Inject most of the time.

The only time we’d need to use @Inject is alongside something like an OpaqueToken - which creates a unique blank token to be used as a dependency injection provider.

The reason we use @Inject is because we cannot use an OpaqueToken as the type of a parameter, for instance this will not work:

const myToken = new OpaqueToken('myValue');

@Component(...)
class ExampleComponent {
  constructor(private token: myToken) {}
}
Here, myToken is not a Type, it’s a value - which means TypeScript cannot compile it. However, when we introduce @Inject alongside an OpaqueToken, things will work out nicely:

const myToken = new OpaqueToken('myValue');

@Component(...)
class ExampleComponent {
  constructor(@Inject(myToken) private token) {
    // use the provider for `token`
  }
}

This gives you an example of using @Inject for manually specifying tokens to be injected, as well as showing that the token can be anything. This means, we’re not restricted to what TypeScript classifies as a “type”.

No comments:

Followers

Link