I recently ran into a problem with an InjectionToken declared in a 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: Cleanup error: Unable to resolve all parameters for SampleComponent: (?).
At the same time, if I try to use the string as the token declared in the module, everything works.
Also, if I declare an InjectionToken directly in the component file, and then install the “providers” directly inside the component decorator, everything works again.
So, the question arises: why the InjectionToken declared inside the module file is not accessible for injection to the component.
source
share