ionic2APP 如何處理返回鍵問題


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

2、封裝一個服務,代碼如下

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;
,請忽略多余沒用的代碼;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM