Recently I've run into problem with InjectionToken, that is declared in module
import {InjectionToken, NgModule} from '@angular/core';
import {SampleComponent} from './sample.component';
export let SOME_TOKEN = new InjectionToken<string>('someToken');
@NgModule({
declarations: [SampleComponent],
providers: [
{provide: SOME_TOKEN, useValue: 'Some value'}
]
})
export class SampleModule {
}
And component class:
import {Component, Inject, OnInit} from '@angular/core';
import {SOME_TOKEN} from './sample.module';
@Component({
selector: 'sample-component',
templateUrl: './sample.component.html',
styleUrls: ['./sample.component.scss']
})
export class SampleComponent implements OnInit {
constructor(@Inject(SOME_TOKEN) private someValue: string) { }
ngOnInit() {
console.log(this.someValue);
}
}
All this gives me an error: Uncaught Error: Can't resolve all parameters for SampleComponent: (?).
At the same time if I try to use string as a token, that declared in module, everything works.
Also, if I declare InjectionToken directly at component file, and then set 'providers' directly inside component decorator, everything works again.
So the question is: why InjectionToken that is declared inside module file is not available for injection to component.
According to @yurzui, there is a circular dependency. Moving token to separate file helped.
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