As per the Ionic documentation I could load Ionic LoadingController using this piece of code:
ionViewLoaded() {
let loader = this.loading.create({
content: 'Getting latest entries...',
});
loader.present().then(() => {
this.someService.getLatestEntries()
.subscribe(res => {
this.latestEntries = res;
loader.dismiss();
});
});
}
This works fine if I am just making 1 ajax request. But I have 5 requests to be made and if I hide / show loading controller like this it leads to flickering of the screens.
Is there a way where I can present the loadingController but then dismiss()
only when all of the Ajax requests have been completed?
EDIT:
Requests do not depend upon one another. They are independent. What I am looking for is a way to get notified when all observable's request is completed. That way I could dismiss the LoadingController when all of them complete.
I'm using following utility in my app. This would also work for multiple steps or/and pages if we want to show the same loader and need to change loader text at different steps.
We can call showLoader() multiple times, would need to ultimately call hideLoader().
@Injectable()
export class Utility {
loader: any = null;
constructor(private _alertCtrl: AlertController,
private _loadingController: LoadingController) {
}
private showLoadingHandler(message) {
if (this.loader == null) {
this.loader = this._loadingController.create({
content: message
});
this.loader.present();
} else {
this.loader.data.content = message;
}
}
private hideLoadingHandler() {
if (this.loader != null) {
this.loader.dismiss();
this.loader = null;
}
}
public showLoader(message) {
this.showLoadingHandler(message);
}
public hideLoader() {
this.hideLoadingHandler();
}
}
You should not use multiple subscribe, and if your requests do not depend on each other you can use the combineLatest
operator, so all requests will execute concurently, and get notified when they have all completed :
ionViewLoaded() {
let loader = this.loading.create({
content: 'Getting latest entries...',
});
let loaded = Observable.combineLatest(
this.someService.getLastEntries().do((entries) => {
//do stuff with last entries
}),
this.someOtherServices.getOtherStuff().do((stuff) => {
// do stuff with stuff
})
// etc...
)
loader.present().then(() => loaded.toPromise()).then(() => loader.dismiss());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With