ionic2APP 如何處理返回鍵問題

一、APP中不免會有自定義各類modal、alert,modal或alert處於激活狀態時android用戶按物理返回鍵,頁面被返回,而這些彈窗切沒有被返回,一種解決辦法是能夠在每一個組件內用生命週期鉤子ionViewWillLeave監聽有modal或是alert的頁面,若是處於激活狀態則先關閉它,固然這種狀態簡單卻不高效;android

二、封裝一個服務,代碼以下this

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {TranslateService} from 'ng2-translate';

@Injectable()
export class ToastService {
comfirmSubject = new Subject();

// comfirmObservable$ = this.comfirmSubject.asObservable();
_isActive = false;
gobackWhenClose = false;
model = null;
is_access_modal:boolean = false;

set isActive(active: boolean) {
if(active) {
this._isActive = true;
} else {
this._isActive = false;
if(this.model) {
this.model.dismiss();
this.model = null;
}
}


}

get isActive() {
return this._isActive || this.model;
}

constructor(private translate: TranslateService) {}

// 普通彈框
confirm(params: any) {
this.comfirmSubject.next(params);
this.isActive = true;
}

// 業務成功後彈框,title帶成功的icon
successConfirm(params: any) {
params = Object.assign(params, {
title: `<i class="icon-icons icon-icons-success"></i><span>${params['title'] || this.translate.get('TIPS.WENXINTISHI')['value']}</span>`
});
this.comfirmSubject.next(params);
this.isActive = true;
}

// 業務失敗後彈框
errorConfirm(params: any) {
params = Object.assign(params, {
title: `<i class="icon-icons icon-icons-error"></i><span>${params['title'] || this.translate.get('TIPS.WENXINTISHI')['value']}</span>`
});

// 錯誤提示處理
let feedbacks = this.translate.get('FEEDBACK')['value'];

let content = params['body'];
if (content) {
if (content.indexOf('MSG.CLINETFUNDNOTENOUGH') > -1) { //購買基金餘額不足時,後臺返回數據作了拆分
params['body'] = feedbacks['MSG.CLIENTFUNDNOTENOUGH'] + '<span class="red">'+ content.split('|')[1] + '</span>'
} else {
params['body'] = feedbacks[content] || content;
}
}

this.comfirmSubject.next(params);
this.isActive = true;
}
}

而後在APP.component.ts中去監聽Android物理返回鍵,
}
if ( this.toastService.isActive && !this.toastService.is_access_modal) { // 當前有自定義toast,關閉toast
this.toastService.isActive = false; //包括toast和model
if(this.toastService.gobackWhenClose) {
this.toastService.gobackWhenClose = false;
this.toastService._isActive = false;
this.events.publish('backto');
}
return;
}

其中有多餘的代碼(爲了符合本身業務需求,主要是isActive這個變量及
this.toastService.isActive = false;
,請忽略多餘沒用的代碼;
相關文章
相關標籤/搜索