模块中声明的InjectionToken的@Inject()在angular2中失败 [英] @Inject() for InjectionToken declared in module fails in angular2

查看:316
本文介绍了模块中声明的InjectionToken的@Inject()在angular2中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我遇到了在模块中声明的InjectionToken的问题

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 {
}

和组件类:

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的所有参数:(?).

All this gives me an error: Uncaught Error: Can't resolve all parameters for SampleComponent: (?).

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

At the same time if I try to use string as a token, that declared in module, everything works.

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

Also, if I declare InjectionToken directly at component file, and then set 'providers' directly inside component decorator, everything works again.

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

So the question is: why InjectionToken that is declared inside module file is not available for injection to component.

推荐答案

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

According to @yurzui, there is a circular dependency. Moving token to separate file helped.

这篇关于模块中声明的InjectionToken的@Inject()在angular2中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆