之前很久之前做過這樣的返回鍵操作,當界面上有操作返回時退出此操作,當沒有操作時退出本界面,主界面雙擊返回退出,之前看過了很多的文章,最后發現在ionic4中有一些代碼已經不使用,自己修修補補完成了這樣的操作,代碼為app.component.ts中代碼
import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Platform, NavController } from '@ionic/angular';
import { Toast } from '@ionic-native/toast/ngx';
import { AppMinimize } from '@ionic-native/app-minimize/ngx';
import { Subscription } from 'rxjs';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { ServicesService } from './services.service'
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
providers: [AppMinimize]
})
export class AppComponent {
sideMenuDisabled = true;
backButtonPressed: boolean = false; //用於判斷是否退出
customBackActionSubscription: Subscription;
url: any = '/tabs/index';//初始界面的url
constructor(
private platform: Platform,
private router: Router,
public navController: NavController,//導航控制器
public toast: Toast,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
public serve: ServicesService
)
//上方所有注入 請自行搜索注入
{
this.initializeApp();
this.initRouterListen();
this.platform.ready().then(() => {
this.statusBar.styleDefault();//管理本機狀態欄的外觀,styleDefault使用默認狀態欄(深色文本,淺色背景)。
this.statusBar.hide(); //顯示和隱藏啟動畫面。
this.registerBackButtonAction();//注冊返回按鍵事件
this.keyboardEvent();
this.platform.resume.subscribe();//彈出框
});
}
private keyValue: any = false;//判斷是否返回上一界面
registerBackButtonAction() {
let that = this;
this.customBackActionSubscription = this.platform.backButton.subscribe(() => {
if (that.keyValue) {
that.keyValue = false;//觸發返回鍵操作,當為true時不返回上一界面
return;
}
if (this.serve.get("scan")) { this.serve.set("scan", false); return; }//此處為服務傳值
if (that.url === '/tabs/index') {//判斷是否是初始界面
if (that.backButtonPressed) {
navigator['app'].exitApp();
that.backButtonPressed = false;//退出
} else {
this.toast.show('再按一次退出應用', '1500', 'top').subscribe(
toast => {
console.log(toast);
}
);
that.backButtonPressed = true;
setTimeout(() => that.backButtonPressed = false, 1500);//延時器改變退出判斷屬性
}
} else {
that.navController.back();//返回上一界面
}
});
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
keyboardEvent() {//鍵盤觸發
let that = this;
window.addEventListener('native.keyboardshow', function () {
that.keyValue = true;//鍵盤開啟改變屬性
});
window.addEventListener('native.keyboardhide', function () {
setTimeout(() => { that.keyValue = false; }, 200)//延時器
});
}
initRouterListen() {
this.router.events.subscribe(event => { // 需要放到最后一個執行獲取當前界面的url
if (event instanceof NavigationEnd) {
this.url = event.url;
}
});
}
}
希望能幫到大家少走彎路
