更新
从 Ionic2 RC 开始,现在我们可以使用Nav Guards了。
在某些情况下,开发人员应该能够控制视图的离开和进入。为此,NavController 具有 ionViewCanEnter 和 ionViewCanLeave 方法。类似于 Angular 2 路由守卫,但更多地与 NavController 集成
所以现在我们可以这样做:
someMethod(): void {
// ...
this.showAlertMessage = true;
}
ionViewCanLeave() {
if(this.showAlertMessage) {
let alertPopup = this.alertCtrl.create({
title: 'Exit',
message: '¿Are you sure?',
buttons: [{
text: 'Exit',
handler: () => {
alertPopup.dismiss().then(() => {
this.exitPage();
});
}
},
{
text: 'Stay',
handler: () => {
// need to do something if the user stays?
}
}]
});
// Show the alert
alertPopup.present();
// Return false to avoid the page to be popped up
return false;
}
}
private exitPage() {
this.showAlertMessage = false;
this.navCtrl.pop();
}
我更喜欢使用该this.showAlertMessage属性,因此如果用户尝试退出页面,我们可以更好地控制何时需要显示警报。例如,我们可能在页面中有一个表单,如果用户没有进行任何更改,我们不想显示警报 ( this.showAlertMessage = false),如果表单实际更改了,我们希望显示警告 ( this.showAlertMessage = true)
旧答案
经过几个小时的努力,我找到了解决方案。
我不得不面对的一个问题是,在关闭ionViewWillLeave时也会执行alert,这会使事情变得更加复杂(当view由于按下后退按钮而即将关闭时,会alert出现,但是当您单击ok时,会触发事件再次打开alert,以此类推...)。
要记住的另一件事是ActionSheetsandAlerts被添加到navigation stack, 所以this.nav.pop()不是从堆栈中删除当前视图,而是删除alert(因此我们可能会觉得它无法正常工作)。
话虽如此,我找到的解决方案是:
import {Component} from '@angular/core';
import {NavController, NavParams, Alert} from 'ionic-angular';
@Component({
templateUrl: 'build/pages/mypage/mypage.html',
})
export class MyPage{
// ....
confirmedExit: boolean = false;
constructor(private nav: NavController, navParams: NavParams) {
// ...
}
ionViewWillLeave() {
if(!this.confirmedExit) {
let confirm = Alert.create({
title: 'Bye',
message: 'Now leaving',
buttons: [
{
text: 'Ok',
handler: () => {
this.exitPage();
}
}
]
});
this.nav.present(confirm);
}
}
public exitPage(){
this.confirmedExit = true;
this.nav.remove().then(() => {
this.nav.pop();
});
}
}
所以:
- 我使用一个
confirmedExit变量来知道您是否已经单击了 ok 按钮(因此您确认要退出页面,并且我知道下次ionViewWillLeave触发事件时,我不必显示alert)
- 在该
exitPage方法中,首先我从堆栈this.nav.remove()中删除alert,一旦完成,我们将this.nav.pop()返回上一页。