Search code examples
ionic-frameworkionic4

How can i catch data return by AlertController in Ionic 4?


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 ?


Solution

  • 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)
    })