离子警报:等到按下按钮

SoS*_*SoS 2 alert promise ionic-framework

我有一个类Action与它的方法do(),其中IonicAlert被调用。我现在想做的是,Action.do().then( () => { /* do domething */ } ); 仅在单击警报上的“ 确定”后,才调用类似 的名称。

do(): Promise<boolean> {

    let alert = this.alertCtrl.create({
      buttons: [{
        text: 'OK',
        handler: () => {
          alert.dismiss().then( () => { /* do something */ });
          return false;
        }
      }]
    });

    alert.present();
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)

我添加return null;只是为了没有错误,但是它当然不起作用。任何想法,如何解决?谢谢

PS:我也将其发布到了ionic论坛:https : //forum.ionicframework.com/t/ionic-alert-wait-until-button-is-pressed/67448

SoS*_*SoS 5

在此站点的帮助下找到了解决方案:https : //basarat.gitbooks.io/typescript/content/docs/promise.html

do(): Promise<boolean> {
    return new Promise((resolve, reject) => {

      let alert = this.alertCtrl.create({
        buttons: [{
          text: 'OK',
          handler: () => {
            alert.dismiss().then(() => { resolve(true); });
            return false;
          }
        }]
      });

      alert.present();

    });
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这里的版本可以返回true或false:

 showConfirm(): Promise<boolean> {
    return new Promise((resolve, reject) =>{
      const confirm = this.alertCtrl.create({
        title : 'Are you sure ?',
        buttons: [
          {
            text: 'Yes',
            handler:_=> resolve(true)
          },
          {
            text: 'No',
            handler:_=> resolve(false)
          }
        ]
      }).present();
    })
  }
Run Code Online (Sandbox Code Playgroud)

兑现承诺:

this.showConfirm().then((result) => {
        if(result){
          // do something
        }
})
Run Code Online (Sandbox Code Playgroud)