Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create loader once and use it all over the app? - Ionic 3

Everywhere in the blogs & article loader is created in the components. I need to create a loader once and use it all over the app. But the problem is, in ionic 3, we can't dismiss loader manually. It should be dismissed after it has presented such as below correct code:

ionViewLoaded() {
  let loader = this.loading.create({
    content: 'Getting latest entries...',
  });

  loader.present().then(() => {
    this.someService.getLatestEntries()
      .subscribe(res => {
        this.latestEntries = res;
      });
    loader.dismiss();
  });
}

I tried creating loader once using service and use it whenever I wanted all over app. such as follows:

import {Injectable} from '@angular/core';
import { LoadingController } from 'ionic-angular';

@Injectable()
export class BasicService{
    loader: any;    
    constructor(public loadingCtrl: LoadingController){
      //creates loader once so there is less data redundancy
        this.loader = this.loadingCtrl.create({
            content: `loading...`,
        });

    }
    showLoader() { //call this fn to show loader
        this.loader.present();    
    }
    hideLoader() { //call this fn to hide loader
        this.loader.dismiss();
    }
}

But it doesn't work, gives an error such as.

Runtime Error Uncaught (in promise): removeView was not found

So is there any way where can achieve this feat in ionic 3, which can help me with data redundancy?

like image 763
nishil bhave Avatar asked Jan 16 '18 14:01

nishil bhave


2 Answers

  constructor(public loadingCtrl: LoadingController){
      //creates loader once so there is less data redundancy
    }
    showLoader() { //call this fn to show loader
        this.loader = this.loadingCtrl.create({
            content: `loading...`,
        });
        this.loader.present();    
    }

Remove creating LoadingController instance from the controller and add it in the showLoader() function in your service.

like image 65
Sachin Avatar answered Nov 15 '22 14:11

Sachin


You got that error because you call this.loader.dismiss(); when your loader is not presenting. So, the right way is:

showLoader(content?: string) {
    if (this.loader) {
      this.loader.dismiss();
    }
    this.loader = this.loadingCtrl.create({ 
      content: content ? content : "Loading..."
    })
    this.loader.present();
    this.loader.onDidDismiss(()=>{
      this.loader = null;
    })
 }
hideLoader() {
    if(this.loader)
      this.loader.dismiss();
}
like image 45
Duannx Avatar answered Nov 15 '22 14:11

Duannx