0
votes

I have an question about Angular 5 routing.

If I declare routes like this below, the route guard is called every time I route to one of the components via routerLink in html.

const routes: Route[] = [ 
  { path: 'comp1', component: Comp1Component, canActivate: [AuthGuard]},
  { path: 'comp2', component: Comp2Component, canActivate: [AuthGuard]},
  { path: '', component: HomeComponent, canActivate: [AuthGuard]},
]

But if I declare it with a componentless route, the guard is only called when the app starts. And when I switch routes in html the guard is never called again.

const routes: Route[] = [
  { path: '', canActivate: [AuthGuard], children: [
  { path: 'comp1', component: Comp1Component},
  { path: 'comp2', component: Comp2Component}
]}

Why is the route guard in my scenario with componentless parent route not called every time a route to a component?

2
does not it makes sense ? You've added Route Guard for Parent Route. Once Parent is activated, now you're in child route. So why AuthGuard will be invoked ?Ritwick Dey
That makes sense. But if I route back to the parent route the AuthGuard is also not called again. Why is that? Is it because there is no other route at the same level as the parent route?ochs.tobi

2 Answers

1
votes

Guess your guard must implement the CanActivateChild interface.

https://angular.io/api/router/CanActivateChild

const routes: Route[] = [
    { path: '', canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: [
        { path: 'comp1', component: Comp1Component},
        { path: 'comp2', component: Comp2Component}
    ]}
]
1
votes

This is how it should work.

Let's say you have an admin section that you want to guard:

{
    path: 'admin',
    component: AdminComponent,
    canActivate: [AuthGuard],
    children: [..]
}

Once you try to go to /admin your guard will be called. Once you are in the admin section the children will not trigger this guard.

If you want to protect the child routes, then yo uneed to use CanActivateChild

const adminRoutes: Routes = [
  {
    path: 'admin',
    component: AdminComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: '',
        canActivateChild: [AuthGuard],
        children: [
            { path: 'comp1', component: Comp1Component},
            { path: 'comp2', component: Comp2Component}
        ]
      }
    ]
  }
];

The AuthGuard should implement both CanActivate and CanActivateChild

You can find more information in the docs: Route guards