在我的 Ionic 5 应用程序中,我有以下导航路径。
PageHome -> PageA -> PageB
我已经为 PageA 实现了 CanDeactivate 保护。
export class LeavePageGuard implements CanDeactivate<isDeactivatable>{
canDeactivate(
component: isDeactivatable
): Observable<boolean> | Promise<boolean> | boolean {
return component.canPageLeave();
}
}
当用户在保存之前编辑某些内容并按下后退按钮时,我会弹出一个弹出窗口以确认用户是否要离开。
async canPageLeave() {
if (this.byPassNav) {
this.byPassNav = false;
return true;
}
if (JSON.stringify(this.dataOld) != JSON.stringify(this.data)) {
const alert = await this.alertCtrl.create({
header: 'Unsaved Chnages',
message: 'Do you want to leave?',
buttons: [
{
text: 'No',
role: 'cancel',
handler: () => { }
},
{
text: 'Yes'),
role: 'goBack',
handler: () => { }
}
]
});
await alert.present();
let data = await alert.onDidDismiss();
if (data.role == 'goBack') {
return true;
} else {
return false;
}
} else {
return true;
}
}
为了继续前进,PageB我正在使用boolean byPassNav. 我在前进之前将此值设置为 TRUE 并且方法canPageLeave正在返回TRUE。
除以下情况外,前向导航在一种情况下不起作用。
on PageA change some data and click on back button -> Confirmation pop up will open -> Select No -> Confirmation pop up will close and the same page remains open. Select button to move forward to PageB.
这会将导航移动到pageB但也会使页面成为根页面并删除所有路由历史记录。PageB在这个流程之后我无法回头。
编辑:添加代码isDeactivatable
export interface isDeactivatable {
canPageLeave: () => Observable<boolean> | Promise<boolean> | boolean;
}
