之前很久之前做过这样的返回键操作,当界面上有操作返回时退出此操作,当没有操作时退出本界面,主界面双击返回退出,之前看过了很多的文章,最后发现在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;
}
});
}
}
希望能帮到大家少走弯路
