Return value from alert confirmation


#1

Hi,

I created a confirmation alert from one service, then i will call the method from other service. Is there a way to return true or false if yes/no is clicked? so that i will create only 1 confirmation alert. thanks in advance


Create a service to manage app alerts
#2

Dismiss the alert manually using alert.dismiss(). At the controller end, use alert.onDidDismiss to accept the data.

In your service file,

promptAlert()
{
    let alert = this.alertCtrl.create({
        title: 'Yes/No',
        buttons: [
            {
                text: 'Yes',
                handler: () => {
                    alert.dismiss(true);
                    return false;
                }
            }, {
                text: 'No',
                handler: () => {
                    alert.dismiss(false);
                    return false;
                }
            }
        ]
    });

    return alert;
}

In your class file,

let alert = this.alert.promptAlert();

alert.present();

alert.onDidDismiss((data) => {
      console.log('Yes/No', data);
});

#3

Thanks for you reply ! I had to test it in a personal project and helped me a lot. However, I’m still wondering why returning false in the case where the Yes button is pressed? Besides, the data passed in the alert.dismiss method is true so I was wondering why returning false.

Thanks again for the reply !


#4

When you return false, the dialog is not dismissed automatically when the user presses the button. This gives you a way to dismiss it yourself within the handler using alert.dismiss(value).

If you returned false, the dismiss would be called internally by AlertController and your alert.dismiss(value) will never be called.