ionic3双击返回退出应用的方法
路与飞鸟 人气:0ionic3 做双击退出应用的时候按照网上大神的来,从中遇到了一些问题,用this.app.getRootNav().push(MyPage);跳转的页面无法返回,this.app.getActiveNav().pop();这个方法在新的版本中已近被移除了,最后使用另外一种返回方式this.appCtrl.getRootNav().pop();
完整代码:
1.tabs.ts文件
import {Component, ViewChild} from '@angular/core'; import { AboutPage } from '../about/about'; import { ContactPage } from '../contact/contact'; import { HomePage } from '../home/home'; import { MyPage } from '../my/my'; import {Tabs} from "ionic-angular"; @Component({ templateUrl: 'tabs.html' }) export class TabsPage { tab1Root = HomePage; tab2Root = AboutPage; tab3Root = ContactPage; tab4Root = MyPage; @ViewChild('mainTabs') tabs:Tabs; constructor() { } }
2.tabs.html文件
<ion-tabs #mainTabs> <ion-tab [root]="tab1Root" tabTitle="定位" tabIcon="ios-pin-outline" ></ion-tab> <ion-tab [root]="tab2Root" tabTitle="运输管理" tabIcon="ios-paper-outline"></ion-tab> <ion-tab [root]="tab3Root" tabTitle="账单管理" tabIcon="logo-yen"></ion-tab> <ion-tab [root]="tab4Root" tabTitle="我的" tabIcon="ios-contact-outline"></ion-tab> </ion-tabs>
3.app.component.ts文件
import {Component, ViewChild} from '@angular/core'; import {Nav, Platform, ToastController,App} from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { Login } from '../pages/login/login'; import { TabsPage } from '../pages/tabs/tabs'; @Component({ templateUrl: 'app.html' }) export class MyApp { rootPage:any; public backButtonPressed: boolean = false; @ViewChild("myNav") nav: Nav; constructor(public platform: Platform,statusBar: StatusBar, splashScreen: SplashScreen, public toastCtrl: ToastController,public appCtrl:App) { platform.ready().then(() => { this.exitApp(); }); } exitApp() { this.platform.registerBackButtonAction(() => { //控制modal、系统自带提示框 let overlay = this.appCtrl._appRoot._overlayPortal.getActive() || this.appCtrl._appRoot._modalPortal.getActive(); if (overlay) { overlay.dismiss(); return; } let activeVC = this.nav.getActive(); let page = activeVC.instance; if (page.tabs) { let activeNav = page.tabs.getSelected(); if (activeNav.canGoBack()) { return activeNav.pop(); } else { return this.showExit(); } } if (page instanceof Login) {//查看当前页面是否是登陆页面 this.showExit(); return; } this.appCtrl.getRootNav().pop();//剩余的情况返回操作 }); } //双击退出函数 showExit() { if (this.backButtonPressed) { this.platform.exitApp(); } else { this.presentToast();//再按一次退出 this.backButtonPressed = true; setTimeout(() => { this.backButtonPressed = false; }, 2000) } } presentToast() { let toast = this.toastCtrl.create({ message: '再按一次退出应用', duration: 2000, position: 'top', }); toast.onDidDismiss(() => { console.log('Dismissed toast'); }); toast.present(); } }
4.app.html文件
<ion-nav #myNav [root]="rootPage"></ion-nav>
加载全部内容