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

前端 未结 20 2291
逝去的感伤
逝去的感伤 2020-12-08 01:06

I used \"Ionic Loading Controller\" to show a spinner until the data is retrieved then it calls \"dismiss()\" to dismissed it. it works fine, but sometimes when the app alre

20条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 01:27

    Same issue I faced while using Ionic 4 loading controller. After trial and error I got working solution.

    As loading controller functions are using async and await because both are asynchronous functions.

    dismiss() function will called before present() function because, dismiss function will not wait until creating and presenting the loader, it will fire before present() as soon function will call.

    Below is working code,

       loading:HTMLIonLoadingElement;
       constructor(public loadingController: LoadingController){}
    
       presentLoading() {
         if (this.loading) {
           this.loading.dismiss();
         }
         return new Promise((resolve)=>{
           resolve(this.loadingController.create({
            message: 'Please wait...'
          }));
         })
       }
    
      async dismissLoading(): Promise {
        if (this.loading) {
          this.loading.dismiss();
        }
      }
    
      someFunction(){
        this.presentLoading().then((loadRes:any)=>{
          this.loading = loadRes
          this.loading.present()
    
          someTask(api call).then((res:any)=>{
            this.dismissLoading();
          })
        })
      }
    

提交回复
热议问题