IONIC按真机上的返回键时,关闭所有的弹窗

       在IONIC的开发过程中,我们经常遇到这样的情况:当你在手机上,弹出了一个提示,如 退出登录登录? yes / no,但这个时候,你不点击yes,也不点击no,你点击手机的返回时,这个弹框仍然还存在,直到退出这个应用时,这个弹框才关闭掉!

    

针对以上问题,下面是解决方法

   app.component.ts页面

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform, IonicApp, Keyboard, App,MenuController,NavController,ToastController} from 'ionic-angular';


@Component({
  templateUrl: 'app.html'
})

export class MyApp {

  bolBack: boolean = false 

  constructor(
    public platform: Platform,
    public menuCtrl: MenuController,
    public ionicApp: IonicApp,
    public app: App,
    public toastCtrl: ToastController,
    public keyboard: Keyboard) {
		
  this.platform.ready().then(() => {
      this.platform.registerBackButtonAction(() => {		  
	//键盘
        if (this.keyboard.isOpen()) { 
          this.keyboard.close();
          return;
        }
		
	//判断是否有弹出框
        let ejectFrom = 
	  this.ionicApp._loadingPortal.getActive() ||
          this.ionicApp._overlayPortal.getActive() ||     
          this.ionicApp._modalPortal.getActive();
       
        //如果有,就将该弹出框关闭掉,并且结束此事件
        if (ejectFrom) {
          ejectFrom.dismiss();
          return;
        }else if (this.menuCtrl.isOpen()) { 
          this.menuCtrl.close();
          return;
        }
     
        let backNav: NavController = this.app.getActiveNav();		
        if (backNav.canGoBack()) {
          backNav.pop();
        } else {
          this.ExitAPP();
        }
      });
    });
  }
 
  //退出应用方法
  private ExitAPP(): void {
    //如果为true,退出
    if (this.bolBack) {
      this.platform.exitApp();
    } else {   
      this.toastCtrl.create({
        message: '再按一次退出应用程序',
        duration: 2000,
        position: 'bottom'
      }).present();
	  
      this.bolBack = true; 
      setTimeout(() =>
        this.bolBack = false, 2000
      );
    }
  }
 
}

app.module.ts页面

import { IonicApp } from 'ionic-angular';
import { Keyboard } from '@ionic-native/keyboard';
import { MyApp } from './app.component';

export function createTranslateLoader() {
}

@NgModule({
  declarations: [MyApp],
  bootstrap: [IonicApp],
  entryComponents: [MyApp],
  providers: [Keyboard]
})

export class AppModule { }

猜你喜欢

转载自blog.csdn.net/qq_41868796/article/details/82695892