Angular 2将参数传递给构造函数将引发DI异常 [英] Angular 2 passing parameters to constructor throws DI exception
问题描述
我想在构造函数中的组件上设置字符串属性,但是当我尝试类似的操作时
I'm wanting to setup a string property on a component in my constructor, but when I try something like this
@Component({
selector: 'wg-app',
templateUrl: 'templates/html/wg-app.html'
})
export class AppComponent {
constructor(private state:string = 'joining'){
}
}
我收到DI例外
EXCEPTION: No provider for String! (AppComponent -> String)
很明显,注入器正在尝试查找字符串"提供程序,而找不到任何提供程序.
Clearly, the injector is trying to find a 'string' provider, and can't find any.
我应该为这种类型的东西使用哪种模式?例如.将初始参数传递给组件.
What sort of pattern should I be using for this type of thing? Eg. passing initial parameters to a component.
应该避免吗?我应该注入初始字符串吗?
Should it be avoided? Should I be Injecting the initial string?
推荐答案
您可以使用@Input()
属性.
<my-component [state]="'joining'"></my-component>
export class AppComponent {
@Input() state: string;
constructor() {
console.log(this.state) // => undefined
}
ngOnInit() {
console.log(this.state) // => 'joining'
}
}
构造函数通常应仅用于DI ...
Constructor should generally be used just for DI...
但是,如果您确实需要它,可以创建可注入变量(plunker):
But if you really, really need it you can create injectable variable (plunker):
let REALLY_IMPORTANT_STRING = new OpaqueToken('REALLY_IMPORTANT_STRING');
bootstrap(AppComponent, [provide(REALLY_IMPORTANT_STRING, { useValue: '!' })])
export class AppComponent {
constructor(@Inject(REALLY_IMPORTANT_STRING) public state: REALLY_IMPORTANT_STRING) {
console.log(this.state) // => !
}
}
最简单的选择是只设置类属性:
Simplest option is to just set class property:
export class AppComponent {
private state:string = 'joining';
constructor() {
console.log(this.state) // => joining
}
}
@Mark指出,另一种选择是使用服务:
As @Mark pointed out, another option is to use a service:
export class AppService {
public state:string = 'joining';
}
export class AppComponent {
constructor(private service: AppService) {
console.log(this.service.state) // => joining
}
}
这篇关于Angular 2将参数传递给构造函数将引发DI异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!