模块中声明的InjectionToken的@Inject()在angular2中失败

Ale*_*nov 5 dependency-injection angular

最近我遇到了在模块中声明的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 {
}
Run Code Online (Sandbox Code Playgroud)

和组件类:

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);
  }

}
Run Code Online (Sandbox Code Playgroud)

所有这些都给了我一个错误: 未捕获错误:无法解析SampleComponent的所有参数:(?).

同时,如果我尝试使用字符串作为令牌,在模块中声明,一切正常.

另外,如果我直接在组件文件中声明了InjectionToken,然后直接在组件装饰器中设置'providers',那么一切都会再次起作用.

所以问题是:为什么在模块文件中声明的InjectionToken不能用于注入组件.

Ale*_*nov 6

据@yurzui说,存在循环依赖.将令牌移动到单独的文件帮助.

  • 而不是回答你的问题,你应该问yurzui提供作为回答评论,所以你能接受它.如你所愿,它会更有礼貌. (7认同)