在提供 OpaqueToken 方面需要一些帮助。使用 Angular 2 beta-12。如果 provider key 是一个字符串,它工作正常,但在使用 OpaqueToken 时不起作用。在 Child 类中,SF 是未定义的。
父类:
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: 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.
最佳答案
这是因为您在包含父类和子类的模块之间存在循环依赖。
如果您将不透明 token 定义到第三个模块并将其包含在其他模块中,它将起作用。
例如常量模块:
export let SF = new OpaqueToken('sf');
在另外两个模块中:
import { SF } from './constants';
关于 Angular 2 OpaqueToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36436005/