我正在创建一个服务,以便在完成后获取ngAfterViewInit中的数据。
export class AppComponent {
gameData:any;
constructor(private _AppComponentService: AppComponentService) {}
ngOnInit(){
this._AppComponentService.getGameData().subscribe(x => {
this.gameData = x;
});
}
ngAfterViewInit() {
console.log(this.gameData); //Undefined
}
}
答案 0 :(得分:2)
由于.getGameData()
可能是一些异步调用,因此当ngAfterViewInit
被调用时,this.gameData
属性没有值,因为.subscribe()
的回调尚未被调用。< / p>
如果你想为此使用Observables,你可以在{28}中使gameData
成为ReplaySubject
或订阅.getGameData()
:
将gameData
设为ReplaySubject
export class AppComponent {
gameData: ReplaySubject = new ReplaySubject(1);
constructor(private _AppComponentService: AppComponentService) {}
ngOnInit(){
this._AppComponentService.getGameData().subscribe(x => {
this.gameData.next(x);
});
}
ngAfterViewInit() {
this.gameData.subscribe(val => console.log(val));
}
}
使用ReplaySubject
ngAfterViewInit()
即使在this.gameData.next(x)
发出值后订阅,也会收到一个值。
订阅.getGameData()
两次:
export class AppComponent {
observable: Observable; // or EventEmitter depending on what you used in getGameData()
constructor(private _AppComponentService: AppComponentService) {}
ngOnInit(){
this.observable = this._AppComponentService.getGameData();
this.observable.subscribe(x => {
// whatever you need
});
}
ngAfterViewInit() {
this.observable.subscribe(val => console.log(val));
}
}