如何执行此异步功能?

时间:2019-09-12 03:43:15

标签: ionic-framework promise async-await

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

我无法放置持续时间,因为我不知道数据库保存列表需要花费多少时间。...

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');
})

2 个答案:

答案 0 :(得分:0)

您必须使用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();
    }
  );

答案 1 :(得分:0)

尝试一下:

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