Home > Back-end >  CanDeactivate Guard not hiding URL in browser window on cancelling navigation
CanDeactivate Guard not hiding URL in browser window on cancelling navigation

Time:11-20

I am using the skipLocationChange property with true value so I can hide the URL in the browser. It is working fine. But for one of my features, I am using CanDeactivate guard so I can warn the user to save changes before leaving the current page. I am just displaying one pop-up to take confirmation from the user. If the user clicks on "OK" then he is navigating to the target page without any issue also the URL is also hidden in the browser. But If the user clicks on the "Cancel" button then he is staying on the same page but the problem is here current page URL is getting appended to the base URL in the browser. Which I don't want. I just want the URL to be hidden with the cancel case too.

I am also attaching the link to a sample project created using stackblitz: https://stackblitz.com/edit/angular-ivy-uqq8sg?file=src/app/app.component.html

Steps to produce an issue in sample project:

  1. Open the user-details page by clicking on the user-details link.
  2. Fill out the user details form and click on the page-one link then it will show a confirmation window click on cancel.
  3. User will stay on the same page but it will also append the user-details URL in the browser.

Note: This question Router guard skip location change does not give the answer to my question because that using canActivate guard, not the canDeactivate guard. In canActivate guard we use router.navigateByURL method where we can set skipLocationChange to true value but in canDeactivate guard for canceling navigation we don't use a router.navigateByURL method

Thanks in advance.

CodePudding user response:

The code is taken from here

What I changed:
In the component, return pure value, not observer so in the guard I can use it directly

return true; //return of(true)

In the guard, navigate by router service instead of just return false/true

this.router.navigate([state.url], { skipLocationChange: true });

Forked stackblitz

  • Related