【问题标题】:@Inject() for InjectionToken declared in module fails in angular2@Inject() for InjectionToken 在模块中声明在 angular2 中失败
【发布时间】: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&lt;string&gt;('someToken'); 移动到分隔文件。你有循环依赖

标签: angular dependency-injection


【解决方案1】:

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

【讨论】:

  • 与其回答您的问题,不如让 yurzui 提供评论作为答案,以便您接受。如您所愿,这样会更有礼貌。
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2017-02-25
  • 2016-11-24
  • 1970-01-01
  • 2017-06-27
  • 2012-06-18
相关资源
最近更新 更多