Loader Service for Ionic 4

Is there a way to create a Loader service for Ionic 4 (async await) like this:

export class LoaderService {

    loader: HTMLIonLoadingElement;

    constructor(public loadingController: LoadingController) {
    }

    showLoader() {
        if (this.loader) { 
            this.loader.present()
        } else {
            this.loader = this.loadingController.create({
                message: 'Loading',
            }).then(() => {
                this.loader.present()
            })
        }
    }

    hideLoader() {
        this.loader.dismiss();
        this.loader = null;
    }

}

Thanks for help

1 Like

Have you tried it? If so, what happened?

Yes, this code does’nt works with ionic 4 because he want async await…

Did you solve this? I’m with the same problem https://stackoverflow.com/questions/55581422/loadercontroller-ionic-4-hide-from-component-or-page

Still not solved, i’ve postponed it…

Does this work?

async showLoader(): Promise<void> {
    try {
        if (!this.loader) {
            this.loader = await this.loadingCtrl.create({ message: 'Loading' });
        }
        await this.loading.present();
    }
    catch(e) { /* handle errors */ }
}

I solved it this way:

async hideLoading() {
    return await this._loadingController.getTop().then(loadingPresent => loadingPresent ? this._loadingController.dismiss(true) : null);
}

Find the Loader instance and pass the “true” parameter to the dismiss events

2 Likes

Hi,

it worked like that for me

...

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

    ... /* code */

    loading.dismiss();
  }