我正在創建一個服務,在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
}
}
最有可能的,因爲GAMEDATA還沒有準備好。如果在afterViewInit函數中需要gameData,則可以將服務調用移至該函數。 – Sefa
如果我在afterviewinit中移動呼叫,它仍然是未定義的。 – fruitjs
@fruitjs如果你在console.log之外的訂閱當然你仍然會得到undefined,因爲getGameData()是一個異步函數。你能證明你如何使用它? – echonax