0

I have a loading controller in Ionic 4 and I want to dismiss it when i save a list in DB, at the same time i need to route to other page, how can I do it?

I can't put duration because i don't know how many time takes the DB saving the list....

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');
})
Wei Seng Tan
  • 487
  • 3
  • 8

2 Answers2

1

Try this:

loading.present().then( async () => { 
    return this.db.insertList(myList).then( async () => { 
        await loading.dismiss(); 
        this.router.navigateByUrl('/nextPage'); 
    }) 
})
Mauro Semproni
  • 226
  • 1
  • 4
0

You have to use Service for that to implement

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

in your class you can implement

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();
    }
  );
Chanaka Weerasinghe
  • 5,404
  • 2
  • 26
  • 39