How to stop double canDeactivate call when redirecting in target route guard?

Viewed 432

I need to add canDeactivate guard to one of my app routes. In that function I call native confirm function in order to confirm whether the user really wants to leave the page. If users goes to non guard protected route is all seems fine.

There's a problem however when users redirect to a route where there's a guard that redirect to another page. What is happening then is that confirm pop-up appears twice.

I've created a simple reproduction. https://stackblitz.com/edit/can-activate-deactive-problem.

  1. Click on the "Link to forbidden".
  2. Click "ok"
  3. Pop-up appears twice.

Is there any way to work around this problem without some hacky solutions?

can-deactivate.guard.ts

@Injectable({ providedIn: 'root' })
export class CanDeactivateGuard implements CanDeactivate<any> {
  canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
    return confirm('are you sure you want to leave?');
  }
}

can-activate.guard.ts

export class CanActivateGuard implements CanActivateGuard {
  constructor(private router: Router) {}

  canActivate(): Observable<boolean> | Promise<boolean> | boolean {
    this.router.navigate(['/not-allowed']);
    return false;
  }
}
0 Answers
Related