在应用关闭离子2之前显示确认提醒

时间:2016-12-14 21:40:14

标签: ionic2

我使用离子2制作一个应用程序。我正在尝试在关闭应用程序之前获得确认警报。

我该怎么做?

3 个答案:

答案 0 :(得分:6)

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)

答案 1 :(得分:5)

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

https://forum.ionicframework.com/t/show-a-confirmation-alert-before-app-close-ionic/63313

showedAlert: boolean;

constructor(..., public alertCtrl: AlertController) {
}

initializeApp() {
    this.platform.ready().then(() => {
        // Okay, so the platform is ready and our plugins are available.
        // Here you can do any higher level native things you might need.
        StatusBar.styleDefault();
        Splashscreen.hide();
        this.showedAlert = false;

        // Confirm exit
        this.platform.registerBackButtonAction(() => {
            if (this.nav.length() == 1) {
                if (!this.showedAlert) {
                    this.confirmExitApp();
                } else {
                    this.showedAlert = false;
                    this.confirmAlert.dismiss();
                }
            }

            this.nav.pop();
        });

    });
}

confirmExitApp() {
    this.showedAlert = true;
    this.confirmAlert = this.alertCtrl.create({
        title: "Salir",
        message: "¿ Esta seguro que desea salir de la aplicación ?",
        buttons: [
            {
                text: 'Cancelar',
                handler: () => {
                    this.showedAlert = false;
                    return;
                }
            },
            {
                text: 'Aceptar',
                handler: () => {
                    this.platform.exitApp();
                }
            }
        ]
    });
    this.confirmAlert.present();
}

答案 2 :(得分:1)

Ionic 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();  
  }
相关问题