使用Ionic2 / angular2进行设备(Android)后退按钮点击检测

时间:2016-11-21 05:04:25

标签: angular ionic2

我可以使用以下代码检测设备(Android)后退按钮单击事件。但点击后退按钮后,它会返回一级并打开确认对话框。

如何使用ionic2避免此行为(转到上一个屏幕)?

registerBackButtonListener() {              
        document.addEventListener('backbutton', () => {           
            let backBtnCnfirm = this.alertCtrl.create({
              message: 'Do you want to close the App?',
              buttons: [
              {
               text: 'Yes',
               handler: () => {
               this.platform.exitApp();
              }
            },
            {
             text: 'No',
             handler: () => {
            }
          }
        ]
       });
        backBtnCnfirm.present();
        }, false);
    }

1 个答案:

答案 0 :(得分:0)

后退按钮将调用navCtrl.pop(),因此返回上一页。 Ionic提供生命周期事件,例如viewDidEnter,viewWillEnter,viewWillLeave等。

在代码中创建此功能时:

ionViewWillLeave(){
   this.alertCtrl.create({
     message: 'Do you want to close the App?',
              buttons: [
              {
                text: 'Yes',
                handler: () => {
                  this.platform.exitApp();
               }
             },
             {
              text: 'No',
              role: 'cancel'
            }
           ]
   }).present();
}

Ionic将在navCtrl.pop()执行之前执行此操作。

注意:这将执行页面将离开的时间(因此在手动推送或弹出时),但我认为您足够聪明,可以找到解决方法(布尔检查f.e。)

(我不知道你的要求,但我发现在按下后退按钮时显示这样的消息很糟糕,通常人们会想要回页)