-1

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

Hasan Kanaan
  • 99
  • 1
  • 11
  • Yes, It calls. You can cache them locally to avoid the hectic burden on each route navigation – Muni Kumar Gundu Sep 07 '20 at 12:35
  • just what is the point of always returning false in the end? I believe you wanted to put return instead of `await` keyword: `return this._agencyService...getMyPromise()`. in this way your returning value inside of `then` would matter – Andrei Sep 07 '20 at 12:37

1 Answers1

2

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.

hyperdrive
  • 1,786
  • 5
  • 19
  • 33
  • I was observing my network tab , I saw that the api was called only once – Hasan Kanaan Sep 07 '20 at 13:02
  • @HasanKanaan You sure? If a Route has a guard, it will always run the guard if the route matches the pattern. https://stackblitz.com/edit/angular-ivy-eah5m6 – hyperdrive Sep 07 '20 at 13:17