我想在构造函数中的组件上设置字符串属性,但是当我尝试这样的东西时
@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)
显然,注入器正试图找到一个“字符串”提供者,但找不到任何.
我应该为这类事物使用什么样的模式?例如.将初始参数传递给组件.
应该避免吗?我应该注入初始字符串吗?
您可以使用@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 …
但如果你真的需要它,你可以创建注射变量(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) // => !
}
}
最简单的选择是设置类属性:
export class AppComponent {
private state:string = 'joining';
constructor() {
console.log(this.state) // => joining
}
}
正如@Mark所指出的,另一种选择是使用服务:
export class AppService {
public state:string = 'joining';
}
export class AppComponent {
constructor(private service: AppService) {
console.log(this.service.state) // => joining
}
}