Search code examples
angular2-routing

CanDeactivate changing the window history


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


Solution

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