Sim*_*lla 9 angular2-directives angular
我想在构造函数中的组件上设置字符串属性,但是当我尝试这样的东西时
@Component({
selector: 'wg-app',
templateUrl: 'templates/html/wg-app.html'
})
export class AppComponent {
constructor(private state:string = 'joining'){
}
}
Run Code Online (Sandbox Code Playgroud)
我得到DI例外
EXCEPTION: No provider for String! (AppComponent -> String)
Run Code Online (Sandbox Code Playgroud)
很明显,注入器正试图找到一个"字符串"提供者,但找不到任何.
我应该为这类事物使用什么样的模式?例如.将初始参数传递给组件.
应该避免吗?我应该注入初始字符串吗?
Sas*_*sxa 19
您可以使用@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'
}
}
Run Code Online (Sandbox Code Playgroud)
构造函数通常只用于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) // => !
}
}
Run Code Online (Sandbox Code Playgroud)
最简单的选择是设置类属性:
export class AppComponent {
private state:string = 'joining';
constructor() {
console.log(this.state) // => joining
}
}
Run Code Online (Sandbox Code Playgroud)
正如@Mark所指出的,另一种选择是使用服务:
export class AppService {
public state:string = 'joining';
}
export class AppComponent {
constructor(private service: AppService) {
console.log(this.service.state) // => joining
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16539 次 |
| 最近记录: |