离子3:用手机的后退按钮关闭模态

V. *_*vet 6 javascript android cordova ionic3

我尝试在我的Ionic App中覆盖手机的后退按钮.

如果我不在页面中,此代码允许我打开模式以关闭应用程序,否则关闭页面.

但这不允许我关闭一个打开的模态.如何检测我是否处于模态中以关闭它?

platform.registerBackButtonAction(() => {

      let nav = app.getActiveNav();
      let activeView: ViewController = nav.getActive();
      console.log(activeView);

      if(activeView != null){
        if(nav.canGoBack()) {
          activeView.dismiss();
        } else{
          let alert = this.alertCtrl.create({
            title: this.pdataManager.translate.get("close-app"),
            message: this.pdataManager.translate.get("sure-want-leave"),
            buttons: [
              {
                text: this.pdataManager.translate.get("no"),
                handler: () => {
                  this.presentedAlert = false;
                },
                role: 'cancel',
              },
              {
                text: this.pdataManager.translate.get("yes"),
                handler: () => {
                  this.presentedAlert = false;
                  this.platform.exitApp();
                }
              }
            ]
          });
          if(!this.presentedAlert) {
            alert.present();
            this.presentedAlert = true;
          }
        }
      }
    });
  }
Run Code Online (Sandbox Code Playgroud)

小智 11

1.Import IonicApp:

import {IonicApp } from 'ionic-angular';
Run Code Online (Sandbox Code Playgroud)

2.添加到您的构造函数:

  private ionicApp: IonicApp
Run Code Online (Sandbox Code Playgroud)

3.在你的platform.registerBackButtonAction中添加:

let activeModal=this.ionicApp._modalPortal.getActive();
if(activeModal){
     activePortal.dismiss();
      return;
   }
Run Code Online (Sandbox Code Playgroud)

我在这里找到答案:https: //github.com/ionic-team/ionic/issues/6982


Dwl*_*hod 3

您可以为模式指定页面名称,并且可以从应用程序中的任何位置访问它。尝试这个..

import { App } from 'ionic-angular';

    constructor(public app: App){

    }

        platform.registerBackButtonAction(() => {

              let nav = this.app.getActiveNav();
              let view = nav.getActive().instance.pageName;


              if (view == YOU_PAGE_NAME) {
                //You are in modal
              } else {
                //You are not in modal
              }
        });
Run Code Online (Sandbox Code Playgroud)

在你的模态中

pageName = 'YOU_PAGE_NAME';
Run Code Online (Sandbox Code Playgroud)