@Inject used for useValue provider type, If there is a value that should in injected instead of class than use @Inject.
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”.
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:
Post a Comment