Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent multiple Ionic Alerts from stacking up

How can I detect if ionic 2 alert ui component instance is already open in order not to present another alert ?

like image 938
Evan Lévesque Avatar asked Oct 09 '16 06:10

Evan Lévesque


Video Answer


2 Answers

I have another idea that you can assign message for a variable and check new message is equal to it or not. If equal, return. This is my code and hope you enjoy with it.

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

@Injectable()
export class AlertProvider {

  public showingMessage = ""

  constructor(
    private alertController: AlertController
  ) {}

  showAlert(message) {
    // Check this message is showing or not
    if (message === this.showingMessage) {
      return
    }

    this.showingMessage = message
    this.alertController.create({
      title: "APP_NAME",
      message: message,
      buttons: [{
        text: "OK",
        handler: () => {
          this.showingMessage = ""
        }
      }]
    }).present()
  }
}
like image 141
Luat Vu Dinh Avatar answered Sep 30 '22 10:09

Luat Vu Dinh


I ended up writing a wrapping provider for Ionic's Alert controller like so :

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

@Injectable()
export class Alert {
  public alertPresented: any;
  constructor(public alertCtrl: AlertController) {
    this.alertPresented = false
  }

  present(title, subTitle) {
    let vm = this
    if(!vm.alertPresented) {
      vm.alertPresented = true
      vm.alertCtrl.create({
        title: title,
        subTitle: subTitle,
        buttons: [{
          text: 'OK',
          handler: () => {
            vm.alertPresented = false
          }
        }],
      }).present();
    }
  }
}

where alertPresented flag prevents more than one instance from being presented

like image 25
Evan Lévesque Avatar answered Sep 30 '22 09:09

Evan Lévesque