石头皮

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;
,请忽略多余没用的代码;

posted on 2017-07-24 18:43  石头皮  阅读(1720)  评论(0编辑  收藏  举报

导航