我如何在 Ionic 4 中通过 AlertController 捕获数据 return?

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

我有调用 AlertController 的 AlertService,而 alertController 有这个方法,

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();
  }

一旦我在另一个组件中调用此方法,

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

alertData 是空的,我这里做错了什么?

我稍微修改了你的代码。

这是我的解决方案。

  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  
}

例如,在 ngOnInit 中它调用这样的函数:

   this._alert.presentAlertPrompt().then((res) => {
  console.log(res)
})