Ionic 5 Loading Controller present/dismiss best practice

Hi guys,
I migrated my app from ionic 3 to 5. The work was not complicated but I have problems managing the loading.

I developed a dedicted service to manage loader:

  async showLoadingSpinner() {
    const loading = this.loadingCtrl.create({
      message: 'Please wait...'
    });

    return await loading.then(res => {
      console.log('Loading show!', res);
      res.present();
    });
  }

  async dismissLoadingSpinner() {
      return this.loadingCtrl.dismiss().then((res) => {
        console.log('Loading dismissed!', res);
      }).catch((error) => {
        console.log('error', error);
      });
  }

I have two methods, one to show the spinner and one to dismiss it.

How use it:

      me.utils.showLoadingSpinner();
   
      this.restClient.register().subscribe(response => {

        me.utils.dismissLoadingSpinner();
        ...

      }, errorData => {

        me.utils.dismissLoadingSpinner();
       
      }, () => {
        
      });

    }

Before to call my rest remote api, I invoke showLoadingSpinner.
When the rest api has been completed ot it generate error, I call dismiss method

Very simple approach.

Unfortunately, randomly the component is not dismissed.

I tried to insert a sleep before the invoke dismiss method and in this scenario, it works but it is a big workaround and I don’t like it.

I have read many articles but I did not understand which is the right solution to implement.

Help me please
L

  async presentAlertMultipleButtons() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: 'Alert',
      subHeader: 'Subtitle',
      message: 'This is an alert message.',
      buttons: ['Cancel', 'Open Modal', 'Delete']
    });

    await alert.present();
    const { data } = await modal.onDidDismiss();
   
  }

And in your case, you need to store the modal variable as property of the service (so this.modal), where the separete modals handle and return whatever you need (like this.modals.dismissModal())

I need to manage Loading Controller, not Alert Controller

You’re not awaiting the showLoadingSpinner method, which means it’s called asynchronously and it might not be created when dismissLoadingSpinner is called. showLoadingSpinner has to be awaited as well when you use it

 async showLoadingSpinner() {
    const res = await this.loadingCtrl.create({
      message: 'Please wait...'
    });
   return res.present()
  }

and then

await me.utils.showLoadingSpinner()

Same structure. Check the docs