1

I have AlertService which calls AlertController, and alertController has this method,

async presentAlertPrompt() {
    const alert = await this._alertController.create({
      cssClass: 'my-custom-class',
      header: 'Add Comment!',
      inputs: [
        {
          name: 'comment',
          type: 'textarea',
          placeholder: 'Comment'
        }
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            console.log('Confirm Cancel');
          }
        }, {
          text: 'Ok',
          handler: (alerData) => {
            return alertData
          }
        }
      ]
    });

    await alert.present();
  }

and once i invoke this method in another component and,

 this._alert.presentAlertPrompt().then((data) => {
      console.log('Alert respone',data)
    })

alertData is empty, what i'm doing wrong here ?

pl-jay
  • 970
  • 1
  • 16
  • 33

1 Answers1

2

I have changed your code a bit.

Here is my solution.

  async presentAlertPrompt() {

    let dataVar

    let oKClicked = false;

    const alert = await this._alertController.create({
      cssClass: 'my-custom-class',
      header: 'Add Comment!',
      inputs: [
        {
          name: 'comment',
          type: 'textarea',
          placeholder: 'Comment'
        }
      ],
      buttons: [
        {
          text: 'Cancel',
          cssClass: 'secondary',
          handler: () => {

            alert.dismiss();
            return false;
        }
        }, {
          text: 'Ok',
          handler: () => {
            oKClicked = true;
        }
        }
      ]
    });

    await alert.present();
    
    await alert.onDidDismiss().then((data) => {

        if(oKClicked){
            dataVar = data.data.values.comment;
        }
    })
    
    return dataVar  
}

And in the ngOnInit for example it calls the function like this:

   this._alert.presentAlertPrompt().then((res) => {
  console.log(res)
})
  • It's worth noting that you can get the data in both `onDidDismiss` and `onWillDismiss`. Also, if you `await` either of the two you can do e.g. `const data = alert.onDidDismiss()` which may be more readable. – Juraj Jun 12 '20 at 14:34