Ionic2 在应用程序关闭之前显示确认警报2

Ionic2 在应用程序关闭之前显示确认警报2,ionic2,Ionic2,我用离子2做了一个应用。我正在尝试在关闭应用程序之前获取确认警报 我怎么做 export class MyApp{ constructor(public alert: AlertController,public platform: Platform){} exit(){ let alert = this.alert.create({ title: 'Confirm', message: 'Do you want to exit?',

我用离子2做了一个应用。我正在尝试在关闭应用程序之前获取确认警报

我怎么做

export class MyApp{  
  constructor(public alert: AlertController,public platform: Platform){}  
  exit(){
      let alert = this.alert.create({
        title: 'Confirm',
        message: 'Do you want to exit?',
        buttons: [{
          text: "exit?",
          handler: () => { this.exitApp() }
        }, {
          text: "Cancel",
          role: 'cancel'
        }]
      })
      alert.present();
  }
  exitApp(){
    this.platform.exitApp();
  }
}
如果要启用后退按钮退出,请为其添加事件侦听器并调用
exit
函数


您可以使用
this.platform.registerBackButtonAction(this.exit)

我可以自己找到正确的解决方案:


离子2+快速解决方案:在您的
app.component.ts
中尝试

ngOnInit() {
    this.platform.registerBackButtonAction(() => {
      if (this.nav.canGoBack()) {
        this.nav.pop();
      } else {
        // Currently on root page
        this.appClosePromt();
      }
    }, 1);
  }

  appClosePromt() {
    let alert = this.alertCtrl.create({
      title: '',
      message: 'Do you want to exit?',
      buttons: [
        {
          text: 'No',
          role: 'cancel',
          handler: () => {
            // Dismiss
          }
        },
        {
          text: 'Exit',
          handler: () => {
            this.platform.exitApp();
          }
        }
      ]
    });
    alert.present();  
  }

即使推送了页面,它也会退出应用程序,如果打开了任何页面,它也不应该退出。您需要在此之前在if块中添加一个返回。nav.pop();
ngOnInit() {
    this.platform.registerBackButtonAction(() => {
      if (this.nav.canGoBack()) {
        this.nav.pop();
      } else {
        // Currently on root page
        this.appClosePromt();
      }
    }, 1);
  }

  appClosePromt() {
    let alert = this.alertCtrl.create({
      title: '',
      message: 'Do you want to exit?',
      buttons: [
        {
          text: 'No',
          role: 'cancel',
          handler: () => {
            // Dismiss
          }
        },
        {
          text: 'Exit',
          handler: () => {
            this.platform.exitApp();
          }
        }
      ]
    });
    alert.present();  
  }