【发布时间】:2018-03-28 02:35:20
【问题描述】:
我有一个 Ionic 2 应用程序,它使用 ionViewCanLeave() navGuard 来显示确认消息。这很好用;用户会看到一个确认对话框,如果他们愿意,可以选择不离开。这是它的代码:
// About to leave
ionViewCanLeave() {
if(!this.allowedToLeave) {
return new Promise((resolve, reject) => {
let confirm = this.alertCtrl.create({
title: 'Are you sure?',
message: 'Are you sure?',
buttons: [{
text: 'OK',
handler: () => {
this.allowedToLeave = true;
resolve();
},
}, {
text: 'Cancel',
handler: () => {
reject();
}
}],
});
confirm.present();
});
}
}
我现在需要检查来自storage 的附加变量。为了得到那个变量,我需要一个承诺。我的代码如下:
// About to leave
ionViewCanLeave() {
this.storage.get('safe_to_leave').then((val) => {
this.safeToLeave = val;
if(!this.allowedToLeave && !this.safeToLeave) {
return new Promise((resolve, reject) => {
let confirm = this.alertCtrl.create({
title: 'Are you sure?',
message: 'Are you sure?',
buttons: [{
text: 'OK',
handler: () => {
this.allowedToLeave = true;
resolve();
},
}, {
text: 'Cancel',
handler: () => {
reject();
}
}],
});
confirm.present();
});
}
});
}
这里发生的情况是,页面从导航堆栈中弹出,然后显示确认对话框。看起来ionViewCanLeave() 没有等待存储调用运行,因为它是异步的。
我怎样才能解决这个问题?
【问题讨论】:
-
与您的问题无关:您确定
if条件正确吗?不应该是||而不是&&?只是通过变量的名称来猜测...... -
我只想说你的问题帮助我防止了使用alerCtrl的页面离开,这个问题我花了4天时间才解决,谢谢
标签: javascript angular ionic-framework ionic2 promise