I have an Ionic 2 application that uses ionViewCanLeave() navGuard to display a confirmation message. This works great; the user displays a confirmation dialog box and may not leave it if he wants. Here is the code for it:
// 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(); }); } }
Now I need to check the extra variable here from storage . To get this variable, I need a promise. My code is as follows:
// 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(); }); } }); }
However, what happens here is that the page is pushed out of the navigation stack, and then a confirmation dialog is displayed. It seems that ionViewCanLeave() not waiting for a call to the storage call, since it is asynchronous.
How can I get around this?
source share