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

前端 未结 20 2284
逝去的感伤
逝去的感伤 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:22

    After trying everything, here's what I finally came up with. Seems to be working well so far.

    Trying to make use of setInterval with a 500ms interval. I also tried to keep the function non-async so that it may be easily used in the consuming end.

    import { Injectable } from '@angular/core';
    import { LoadingController } from '@ionic/angular';
    
    @Injectable({ providedIn: 'root' })
    export class UiService {
        constructor(private loading: LoadingController) { }
    
        private loader: HTMLIonLoadingElement;
        private loaderLoading = false;
    
        public showLoading(message: string) {
            this.loaderLoading = true;
            this.loading.create({
                message,
                showBackdrop: true
            }).then(load => {
                this.loader = load;
                load.present().then(() => { this.loaderLoading = false; });
            });
        }
    
        public dismissLoading() {
            const interval = setInterval(() => {
                if (this.loader || !this.loaderLoading) {
                    this.loader.dismiss().then(() => { this.loader = null; clearInterval(interval)});
                } else if (!this.loader && !this.loaderLoading) {
                    clearInterval(interval);
                }
            }, 500);
        }
    }
    

提交回复
热议问题