angularroutesangular8angular-router-guardscanactivate

Angular canActivate function in guard executed twice


I'm using Angular 8, and I have a guard that opens a page in a separate tab using window.open(url) if a specific condition is met, then returns false because I don't want to leave the current page I am on.

I am doing this logic in the canActivate function:

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot):
                                      Observable<boolean | UrlTree> | 
                                      Promise<boolean | UrlTree> | boolean | UrlTree {
  if(condition)  
    window.open(url)

  return false;
}

My problem is that canActivate function is being called twice in a row, which causes the new tab to open twice. How can I solve this?

This is how I route to my guard in app.routing.constant

{
    path: dashboardRoutes.MY_ROUTE,
    component: BlankComponent,
    canActivate: [MyGuard]
},

Solution

  • Found the problem, I was routing both in html component by using [routerLink] and in ts by using this.router.navigate, so this func really was called twice. My mistake, hope this can help anyone who has a similar problem