您可以使用@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
}
}