1. 程式人生 > >IONIC按真機上的返回鍵時,關閉所有的彈窗

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 { }