Ionic: How to not stack multiple toast notifications?
You could store your Toast object in a variable outside your function, and call the dismiss() method before showing the next toast :
Ionic 4
import { ToastController } from '@ionic/angular';
toast: HTMLIonToastElement;
showError(message: string) {
try {
this.toast.dismiss();
} catch(e) {}
this.toast = this.toastController.create({
message: message,
position: 'top',
duration: 5000,
color: 'danger',
showCloseButton: true
});
toast.present();
}
Ionic 3
import { ToastController, Toast } from 'ionic-angular';
toast: Toast;
showError(message: string) {
try {
this.toast.dismiss();
} catch(e) {}
this.toast = this.toastController.create({
message: message,
position: 'top',
duration: 5000,
cssClass: 'danger',
showCloseButton: true
});
toast.present();
}
Here my solution :-)
// ToastService.ts
import { Injectable } from '@angular/core';
import { ToastController, Toast } from 'ionic-angular';
@Injectable()
export class ToastService {
private toasts: Toast[] = [];
constructor(private toastCtrl: ToastController) {}
push(msg) {
let toast = this.toastCtrl.create({
message: msg,
duration: 1500,
position: 'bottom'
});
toast.onDidDismiss(() => {
this.toasts.shift()
if (this.toasts.length > 0) {
this.show()
}
})
this.toasts.push(toast)
if (this.toasts.length === 1) {
this.show()
}
}
show() {
this.toasts[0].present();
}
}
You can check if there is already a toast present or not and create new only if no toast present.
import { ToastController, Toast } from 'ionic-angular';
toast: Toast;
isToastPresent:boolean=false;
show(){
this.isToastPresent?'':this.showError('No network');
}
showError(message: string) {
this.toast = this.toastController.create({
message: message,
duration: 3000,
cssClass: 'danger',
showCloseButton: true
});
toast.present();
this.isToastPresent=true;
this.toast.onDidDismiss(() => {
this.isToastPresent=false;
console.log('Dismissed toast');
});
}