Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent duplicate Toast messages in Ionic

I have implemented toast using ToastController in my ionic2 project . Currently i am facing an issue with the duplicate toast messages . Is there any way to prevent the duplication / overlapping of toast message in ionic2 / angular2

(NB : Duplication means when I click on a button I am displaying a toast , if I click on the same button multiple times the toast messages overlaps ) ?

code

export class <className>{
   constructor(private toast:ToastController){
   }
    showToast(message) {
    let toast = this.toastCtrl.create({
        message: message,
        duration: 2000,
        position: 'bottom'
    })
    toast.present();
   }
}

I am calling this method on an button click .

Edited

  1. with duplicates toast (taken example using toastr , same sitaution is for me) enter image description here

  2. when i enable "prevent notification" , the duplicate toast are not there within the timeout duration . enter image description here

Any help is much appreciated.

like image 578
Arj 1411 Avatar asked Jul 13 '17 07:07

Arj 1411


Video Answer


1 Answers

You can use a property on that page to know if a toast is being shown or not before showing a new one.

Ionic 2/3

import { ToastController, Toast } from 'ionic-angular';

// ...

private isToastVisible: boolean;

constructor(private toastCtrl: ToastController) { }

presentToast() {
  if(this.isToastVisible) {
    return;
  }

  this.isToastVisible = true;

  const toast: Toast = this.toastCtrl.create({
    message: 'User was added successfully',
    duration: 3000,
    position: 'top'
  });

  toast.onDidDismiss(() => {
    this.isToastVisible = false;
  });

  toast.present();
}

Ionic 4/5

import { ToastController } from '@ionic/angular';

// ...

private isToastVisible: boolean;

constructor(private toastCtrl: ToastController) { }

presentToast() {
  if(this.isToastVisible) {
    return;
  }

  this.isToastVisible = true;

  this.toastCtrl.create({
    message: 'User was added successfully',
    duration: 3000,
    position: 'top'
  }).then((toast: HTMLIonToastElement) => {

    toast.onDidDismiss().then(() => {
      this.isToastVisible = false;
    });

    toast.present();
  })      
}
like image 165
sebaferreras Avatar answered Oct 26 '22 22:10

sebaferreras