Attempting to inject an object using an InjectionToken.
In the AppModule I have:
export const tokenConfigKey = new InjectionToken('config');
const tokenBasedConfig = {
provide: tokenConfigKey,
useValue: {
key: 'value'
}
}
And in the AppComponent:
@Component({
selector: 'my-app',
template:`<h1>Hello Angular Lovers!</h1>`
})
export class AppComponent {
constructor(@Inject('config') config,
@Inject(tokenConfigKey) configByToken) {
}
}
This is a complete stacblitz example
Injection using the string key is passing, but injection with the token is failing. Any ideas why?
Here's an article in case anyone wants to play with this
A circular dependency issue could exist due to the fact that the AppModule imports the AppComponent and the AppComponent imports the InjectionToken from the AppModule.
Moving token to separate resolvs the issue:
token.ts
import { InjectionToken } from '@angular/core';
export const BASE_URL = new InjectionToken<string>('BaseUrl');
app.module.ts
@NgModule({
providers: [{ provide: BASE_URL, useValue: { key: 'http://localhost' } }],
app.component.ts
constructor(@Inject(BASE_URL) configByToken) {
console.log(configByToken);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With