角度2不透明令牌 [英] angular 2 OpaqueToken
问题描述
在提供OpaqueToken方面需要一些帮助.使用Angular 2 beta-12.如果提供程序密钥是字符串,则可以正常工作,但在使用OpaqueToken时不起作用.在Child类中,SF未定义.
Need some help with providing an OpaqueToken. Using Angular 2 beta-12. It works fine if provider key is a string, but doesn't work when using OpaqueToken. In Child class, SF is undefined.
父级:
export let SF = new OpaqueToken('sf');
export class A {
testMsg: string = 'hello';
}
@Component({
template: `<child></child>`,
providers: [
provide(SF, {useValue: A}),
provide('justString', {useValue: 'hi'})
]
})
export class App {}
儿童班:
import {Component, Injector, Inject, OpaqueToken} from 'angular2/core'
import {SF, A} from './app'
console.log("******", SF); // undefined
@Component({
selector: 'child',
template: `
$$CHILD Rendered$$ {{a}}
`
})
export class Child {
//constructor(@Inject(SF) private a: A) {} // doesn't work
constructor(@Inject('justString') private a: string) {}
}
我得到的例外:
angular2.min.js:17EXCEPTION:无法解析"Child"(@ Inject(未定义))的所有参数.确保所有参数都用Inject修饰或具有有效的类型注释,并确保'Child'用Injectable修饰.
angular2.min.js:17EXCEPTION: Cannot resolve all parameters for 'Child'(@Inject(undefined)). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'Child' is decorated with Injectable.
推荐答案
这是因为在包含父类和子类的模块之间存在循环依赖性.
It's because you have a cyclic dependency between modules that contain parent and child classes.
如果您将不透明令牌定义到第三个模块中,并将其包含在其他模块中,它将起作用.
If you define your opaque token into a third module and include it in the other ones, it will work.
例如常量模块:
export let SF = new OpaqueToken('sf');
在其他两个模块中:
import { SF } from './constants';
这篇关于角度2不透明令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!