Unexpected behavior when routing to children with componentless route in Angular 5

744 Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

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}
    ]}
]
0
On

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