首页 > 解决方案 > Ionic JavaScript 函数无需等待承诺即可执行

问题描述

我有以下在页面 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 等待获取数据完成,然后再执行所有其他方法,但目前这些方法会立即触发,而获取数据仍然很忙。知道为什么会这样吗?

标签: javascriptangularionic-framework

解决方案


当 Angular 加载组件时,它会运行不同的生命周期钩子(此处为官方文档

在您的情况下,将在您需要更新代码以按顺序运行ngOnInit()之前触发。fetchdata()


推荐阅读