Dismiss alert when another alert is initiated

One alert is shown on the screen…in the background one process is going on which again initiates an alert…so now the previus alert should be dsimissed and the next one must be shown.

can anyone tell hove to achieve this?

alert has a method alert.dismiss() to close it, but I’m guessing you already know that. I think what you might want to do is create an alert service so everybody uses the same alert controller. Here’s mine:

export class Services {

  alert: any;

  constructor(private alertCtrl: AlertController) {}

  public Alert = (title:string, message?:string, actionLabel?:string, actionCallback?:any, cancelLabel?:string):void => {
    let buttons:Array<any> = [
        {
          text: cancelLabel || 'Cancel',
          role: 'cancel',
          handler: () => {
          }
        }
      ];
    if (actionLabel) {
      buttons.push(
        {
          text: actionLabel || 'OK',
          handler: actionCallback
        }
      );
    }
    this.alert = this.alertCtrl.create({
      title: title,
      message: message,
      buttons: buttons
    });
    this.DismissLoading
    this.alert.present();
  }
}

Inject the service into all your components, and then just use this.services.alert(‘Hello!’) whenever you need to alert. I think that this will automatically get you what you are looking for, a new alert will replace the old one. If that is not happening, you can check whether an existing alert is open and close it like this:

if (this.services.alert && !this.services.alert._detached) { this.services.alert.dismiss(); }

(I don’t like using the internal variable _detached but I don’t see another way to tell if an alert exists but has been dismissed.)

2 Likes

I’ve been looking for something similar. Plus a way to dismiss the alert from any other component. This is my actual solution:

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

@Injectable()
export class AlertService {
  private alert: Alert;

  constructor(private alertCtrl: AlertController) {

  }

  public present(options) {
    this.dismiss();
    this.alert = this.alertCtrl.create(options);
    this.alert.present();
  }

  public dismiss() {
    if (this.alert && !this.alert._detached) this.alert.dismiss();
  }

}

I’m still working on this because I have a case in which dismissing an alert will immediately present another one. So, because the new alert is using the same service, the service will close the previous alert, but ionic AlertController will try to close it too after it’s already closed, returning an “Uncaught (in promise): removeView was not found” error

https://forum.ionicframework.com/t/find-out-if-alert-over-active-view/88232/2?u=sreeragsp

checkout this link.it will surely help you out.