Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 234
Deepender Sharma Avatar asked Sep 27 '17 12:09

Deepender Sharma


2 Answers

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;
        }
    }
}
like image 123
Valeriy Katkov Avatar answered Nov 11 '22 06:11

Valeriy Katkov


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;
    }
  }
}
like image 1
Nalin Avatar answered Nov 11 '22 05:11

Nalin