【问题标题】:How can I execute this async function?如何执行此异步功能?
【发布时间】:2019-09-12 22:01:52
【问题描述】:

我在 Ionic 4 中有一个加载控制器,我想在数据库中保存列表时将其关闭,同时我需要路由到其他页面,我该怎么做?

我不能放 duration 因为我不知道数据库保存列表需要多少时间....

const loading = await this.loadingController.create({
  message: 'Please wait...',
});

await loading.present();

this.db.insertList(myList).then(async () => {
  await loading.onDidDismiss();
  this.router.navigateByUrl('/nextPage');
})

【问题讨论】:

    标签: ionic-framework promise async-await


    【解决方案1】:

    试试这个:

    loading.present().then( async () => { 
        return this.db.insertList(myList).then( async () => { 
            await loading.dismiss(); 
            this.router.navigateByUrl('/nextPage'); 
        }) 
    })
    

    【讨论】:

      【解决方案2】:

      你必须使用 Service 来实现

      Ionic 4: "Loading Controller" dismiss() is called before present() which will keep spinner without dismissing

      import { Injectable } from '@angular/core';
      import { LoadingController } from '@ionic/angular';
      
      @Injectable({
        providedIn: 'root'
      })
      export class MyLoadingService {
      
        isLoading = false;
      
        constructor(public loadingController: LoadingController) { }
      
        async presentLoading() {
          this.isLoading = true;
          return await this.loadingController.create({
            duration: 5000,
          }).then(a => {
            a.present().then(() => {
              console.log('presented');
              if (!this.isLoading) {
                a.dismiss().then(() => console.log('abort presenting'));
              }
            });
          });
        }
      
        async dismissLoading() {
          this.isLoading = false;
          return await this.loadingController.dismiss().then(() => console.log('dismissed'));
        }
      }
      

      你可以在课堂上实现

      constructor(public myLoadingService: MyLoadingService, private someService: SomeService)
      
      ngOnInit() {
        this.myLoadingService.present();
        this.someService.getCustomer('1')
        .subscribe(
          customer => {
            this.customer = customer;
            this.myLoadingService.dismiss();
          },
          error => {
            console.log(error);
            this.myLoadingService.dismiss();
          }
        );
      

      【讨论】:

        猜你喜欢
        • 2020-11-07
        • 2012-11-18
        • 2019-03-11
        • 1970-01-01
        • 1970-01-01
        • 2020-01-01
        • 2020-02-26
        • 2019-10-04
        • 2021-11-04
        相关资源
        最近更新 更多