【问题标题】:Loading controller await problem with Ionic加载控制器等待 Ionic 的问题
【发布时间】:2020-11-27 16:37:10
【问题描述】:

在我的 ngOnInit 页面中,我调用一个函数来呈现加载,然后调用我的服务来加载数据。 问题是服务调用在加载开始之前结束。 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。

【问题讨论】:

    标签: ionic-framework ionic4


    【解决方案1】:

    在您的情况下(基于代码),您具有返回承诺(异步)的 presentLoading 函数,因此即使在其中使用 await 语句 - 在 ngOnInit 钩子内部,没有任何内容指示执行等待 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 成为异步方法不会“伤害”,但最好了解它的更多含义:async/await in Angular `ngOnInit`

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      • 2019-05-22
      • 2011-06-27
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 2017-05-18
      相关资源
      最近更新 更多