Route Guard based on an api call

543 Views Asked by At

I have a route guard in angular which returns true or false according to an api call enter image description here

I am using this route guard on multiple routes, my question is : does the api get called for every route I put the route guard on ? As you can see in the following picture , I am using it heavily : s

1

There are 1 best solutions below

2
On

Yes it does. You can also wrap the routes in a parent component, this will only activate once if navigating between child routes.

export const routes: Routes = [
  {
    path: 'error',
    component: ErrorComponent,
  },
  {
    path: 'login',
    component: LoginComponent,
  },
  { path: '', component: MainParentComponent, canActivate: [MainRouteGuard],
    children: [
      { path: '', redirectTo: 'child1', pathMatch: 'full' },
      { path: 'child1', component: ChildComponent },
      { path: 'child2', component: ChildComponent }
    ]
  }
];

Also, keep in mind: Angular will resolve the route patterns in the order they are defined in. So if you are using root '' '/' as the main component route, make sure you define the other routes above main in the routes. Otherwise it will always match, and try to run the guard.

Also, CanActivate can take a bool/promise/observable/UrlTree. So no need to transform them as you have.