import { Component } from '@angular/core'; import { ActionSheetController, AlertController, LoadingController, MenuController, ModalController, NavController, Platform, PopoverController } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { Subscription } from 'rxjs'; import { PublicService } from './PublicService'; import { NavigationEnd, Router } from '@angular/router'; import {filter} from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: 'app.component.html' }) export class AppComponent { private backButtonPressed = false; // 用于判断返回键是否触发 private customBackActionSubscription: Subscription; private url; constructor( private platform: Platform, private splashScreen: SplashScreen, private readonly publicService: PublicService, private readonly navController: NavController, private readonly router: Router, private readonly loadingCtrl: LoadingController, private readonly alertCtrl: AlertController, private readonly modalCtrl: ModalController, private readonly menuCtrl: MenuController, private readonly actionSheetCtrl: ActionSheetController, private readonly popoverCtrl: PopoverController, private statusBar: StatusBar ) { this.initRouterListen(); this.initializeApp(); } initializeApp() { this.platform.ready().then(() => { // this.statusBar.styleDefault(); // // this.statusBar.overlaysWebView(true); // this.splashScreen.hide(); this.registerBackButtonAction(); }); } private registerBackButtonAction() { this.customBackActionSubscription = this.platform.backButton.subscribe( async () => { console.log(this.url, this.backButtonPressed); if ( this.url === '' || this.url === '/' || this.url === '/tabs' || this.url === '/login' || this.url === '/tabs/home' || this.url === '/tabs/collect' || this.url === '/tabs/mine' || this.url === '/tabs/message' ) { // 监测到当前路由,判断是否要退出程序 if (this.backButtonPressed) { navigator['app'].exitApp(); this.backButtonPressed = false; } else { this.publicService.presentToast('再按一次退出应用'); this.backButtonPressed = true; setTimeout(() => (this.backButtonPressed = false), 2000); } } else { this.navController.back(); } } ); } private initRouterListen() { this.router.events.pipe( filter(e => e instanceof NavigationEnd)) .subscribe((e: NavigationEnd) => { this.url = e.url; const fi = this.url.lastIndexOf('/') + 1; const li = this.url.indexOf('?') > -1 ? this.url.indexOf('?') : this.url.length; const tabName = this.url.substring(fi, li); const tabObj = { home: true, collect: true, message: true, mine: true }; if (tabObj[tabName]) { for (const key in tabObj) { if (tabName === key) { this.publicService.event.emit(tabName); } } } }); } }