简体   繁体   中英

Why is the Angular canActivate function guard executed twice when navigating routes

I'm using Angular 5 and have a couple of routes defined. When I navigate routes and put a breakpoint on the canActivate function guard, I see it is executed twice.

I'm asking this because I have to call an external service on each canActivate call, and executing the same service uselessly multiple times causes unnecessary overhead.

Just happened to me, and the problem was this snippet in my AuthGuard :

setActiveWebsite(website: string): void {
    this._website.next(website);
    this.router.navigate([]);  <-- This line here
}

It executed twice because it sets a value, redirects, and then skipped auth because it resolved to true immediately.


Are you, maybe, using route.navigate or a redirect in one of your guards or resolvers ?

Angular 7.1 solves this problem with the router.parseUrl() method, which takes the path name (as set in the routing module) as an argument.

So instead of router.navigate(['__']) or router.navigateByUrl('__') , which by the way should followed by a false return if used as a redirect, you would do the elegant return router.parseUrl('____') .

I exhausted so many variations of the previous methods that I now plan my days around a calendar composed strictly of angular guard logic.

In removing the need for me to travel home every time I wanted check that calendar, this new parseUrl() upgrade has substantially improved my life.

Hat tip to Nate Lapinski and the fantastic Angular In Depth .

It is ran several times because the router has several events to handle. You could test if this is the last event with something like this.

this.router.events.subscribe(event => {
  if(event instanceof NavigationEnd) {
    // Last event, do your thing
  }
});

It is the not the canActivate being executed multiple times, but it is the event that you have subscribed to. In your case it would be the router event.

You can watch for only the last event which is NavigationEnd as explained in the other answer by @trichetriche.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM