Prevent multiple Ionic Alerts from stacking up

前端 未结 4 1276
孤城傲影
孤城傲影 2021-02-20 06:37

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

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-20 07:29

    You can create an AlertService to handle that with more options without inject an event for the buttons

    import { Injectable } from '@angular/core';
    import { AlertController, Alert } from 'ionic-angular';
    
    /**
     * A simple alert class to show only one alert at the same time
     */
    @Injectable()
    export class AlertService {
      currentAlert: Alert
      constructor(private alertCtrl: AlertController) {
      }
    
      show(title, message, buttons: any = [], inputs: any = [], cssClass = '') {
        if (!buttons.length) {
          buttons.push('Ok')
        }
        let alertOptions: any = {
          title: title,
          subTitle: message,
          buttons: buttons,
          cssClass: buttons.length === 2 ? 'confirmAlert' : cssClass
        }
        if (inputs.length) {
          alertOptions.inputs = inputs
        }
        if (!this.currentAlert) {
          this.currentAlert = this.alertCtrl.create(alertOptions)
          this.currentAlert.present()
          this.currentAlert.onDidDismiss(() => {
            this.currentAlert = null
          })
        }
        return this.currentAlert
      }
    }
    

    Regards, Nicholls

提交回复
热议问题