我有以下在ngOnInit页面上调用的方法
ngOnInit() {
this.devicesinfo.fetchdata().then(response => {
this.deviceSub = this.devicesinfo.alldevices.subscribe(alldevices => {
this.deviceinfosarr = alldevices;
alert(JSON.stringify(this.deviceinfosarr[0]));
this.doneloading = true;
} );
});
}
这里是设备信息服务类中的获取数据方法。
async fetchdata() {
return await new Promise((resolve, reject) => {
this.getuserdevicesIDs().then(response => {
alert(this.arrIDs.IDs+ ' IDs I have');
// get all of the IDS of the devices a user owns.
// tslint:disable-next-line: prefer-for-of
this.getdeviceinfo().then(res => { // Get the information of a specific device
const device = (res);
this.deviceinfos[0] = device;
});
});
resolve(true); // when you want to return a value in promise
});
// tslint:disable-next-line: prefer-const
// tslint:disable-next-line: no-var-keyword
}
我的目标是让NgOnit在完成所有其他方法之前先等待获取数据完成,然后在获取数据仍然繁忙的同时立即触发这些方法。知道为什么会这样吗?
[当角度加载组件时,它运行不同的生命周期挂钩,请查看[Official docs here)
在您的情况下,ngOnInit()
将在fetchdata()
之前触发,您需要更新代码以按顺序运行。