【发布时间】:2017-05-17 20:13:45
【问题描述】:
最近我遇到了在模块中声明的 InjectionToken 的问题
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 {
}
及组件类:
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);
}
}
所有这些都给了我一个错误: 未捕获的错误:无法解析 SampleComponent 的所有参数:(?)。
同时,如果我尝试使用在模块中声明的字符串作为标记,一切正常。
另外,如果我直接在组件文件中声明 InjectionToken,然后直接在组件装饰器中设置 'providers',一切都会再次运行。
所以问题是:为什么在模块文件中声明的 InjectionToken 不可用于注入组件。
【问题讨论】:
-
将
export let SOME_TOKEN = new InjectionToken<string>('someToken');移动到分隔文件。你有循环依赖
标签: angular dependency-injection