Monday, 26 October 2020

Navigation issue with CanDeactivate guard in Ionic 5

In my Ionic 5 application I have the following navigation path.

PageHome -> PageA ->  PageB

I have implemented CanDeactivate guard for PageA.

export class LeavePageGuard implements CanDeactivate<isDeactivatable>{
  canDeactivate(
    component: isDeactivatable
  ): Observable<boolean> | Promise<boolean> | boolean {
    return component.canPageLeave();
  }
}

When user edit something and press back button before saving I am raising a popup to confirm if user wants to leave.

  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;
    }
  }

To move forward to PageB I am using a boolean byPassNav. I am setting this value to TRUE before moving forward and the method canPageLeave is returning TRUE.

The forward navigation is not working in one scenario except the following.

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.

This will move the navigation to pageB but also will make the page as Root Page and remove all route history. I can't go back from PageB after this flow.



from Navigation issue with CanDeactivate guard in Ionic 5

No comments:

Post a Comment