加载控制器等待离子的问题

Loading controller await problem with Ionic

在我的 ngOnInit 页面中,我调用了一个函数来呈现 Loading,然后调用我的服务来加载数据。 问题是服务调用在加载开始之前结束。 await 怎么可能?

loading: any;
...
ngOnInit() { 
    this.presentLoading();
    this.myService.get().subscribe((item)=>{
      console.log('dismiss');
      this.loading.dismiss();
    }, ()=>{
      this.loading.dismiss();
    })
  }

  async presentLoading() {
    this.loading = await this.loadingController.create({
      message: 'Loading...',
      duration: 20000
    });
    console.log('presentLoading')
    await this.loading.present();
  }

在控制台中我可以看到:

dismiss
ERROR TypeError: Cannot read property 'dismiss' of undefined....
presentLoading

我正在使用 Ionic4。

在你的情况下(基于代码)你有 presentLoading 函数 returns 一个承诺(异步),所以即使在它里面你正在使用 await 语句 - 在 ngOnInit 钩子里面没有任何指示执行await for the presentLoading.

你可以这样做:

  async ngOnInit() { 
    await this.presentLoading();
    this.myService.get().subscribe((item)=>{
      console.log('dismiss');
      this.loading.dismiss();
    }, ()=>{
      this.loading.dismiss();
    })
  }

此外,由于您正在使用 Onservables,因此在“已完成”函数中调用 dismiss 可能是有意义的:

  async ngOnInit() { 
    await this.presentLoading();
    this.myService.get().subscribe((item)=>{
      console.log('dismiss');
    }, (error)=>{
      console.log(error);
    }, (completed)=>{
      this.loading.dismiss();
    }
  })

注意事项 - 使 ngOnInit 成为一个异步方法并没有“伤害”,但最好了解它具有的更多含义: