我正在创建一个服务,在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