I am facing some issue with canDeactivate() whenever it returns false it is changing the window history as when it became true and if i hit the back button. I am navigating to some other URL or out of the app itself.
Please help me
Here is the issue, but it still isn't fixed.
As a workaround, you can manually put the active url back to the history:
export class CanDeactivateGuard implements CanDeactivate<any> {
constructor(
private readonly location: Location,
private readonly router: Router
) {}
canDeactivate(component: any, currentRoute: ActivatedRouteSnapshot): boolean {
if (myCondition) {
const currentUrlTree = this.router.createUrlTree([], currentRoute);
const currentUrl = currentUrlTree.toString();
this.location.go(currentUrl);
return false;
} else {
return true;
}
}
}
The issue is still present with Angular routing and below is what worked for me.
Trick is to use this.router.navigate([currentUrl], { skipLocationChange: true });
Full code:
export class CanDeactivateGuard implements CanDeactivate<any> {
constructor(
private location: Location,
private router: Router
) { }
canDeactivate(component: any,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot): boolean {
if(canDeactivateCondition) {
return true;
} else {
const currentUrl = currentState.url;
if (this.location.isCurrentPathEqualTo(currentUrl)) {
// https://github.com/angular/angular/issues/13586
this.router.navigate([currentUrl], { skipLocationChange: true });
} else {
// A browser button has been clicked or location.back()/forward() invoked. Restore browser history
history.pushState(null, null, location.href);
}
return false;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With