The angular2 documentation about Route Guards left me unclear about when it is appropriate to use a CanActivate
guards vs. a CanActivateChild
guard in combination with component-less routes.
TL;DR: what's the point in having canActivateChild
when I can use a component-less routes with canActivate
to achieve the same effect?
Long version:
We can have multiple guards at every level of a routing hierarchy. The router checks the CanDeactivate and CanActivateChild guards first, from deepest child route to the top. Then it checks the CanActivate guards from the top down to the deepest child route.
I get that CanActivateChild
is checked bottom up and CanActivate
is checked top down. What doesn't make sense to me is the following example given in the docs:
@NgModule({
imports: [
RouterModule.forChild([
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
canActivateChild: [AuthGuard],
children: [
{ path: 'crises', component: ManageCrisesComponent },
{ path: 'heroes', component: ManageHeroesComponent },
{ path: '', component: AdminDashboardComponent }
]
}
]
}
])
],
exports: [
RouterModule
]
})
export class AdminRoutingModule {}
So the admin
path has a component-less route:
Looking at our child route under the AdminComponent, we have a route with a path and a children property but it's not using a component. We haven't made a mistake in our configuration, because we can use a component-less route.
Why is the code in this case inserting the AuthGuard
in the child and in the root component (path admin
)? Wouldn't is suffice to guard at the root?
I have created a plunkr based on the sample that removes the canActivateChild: [AuthGuard]
and adds a logout button on the AdminDashboard
. Sure enough, the canActivate
of the parent route still guards, so what's the point in having canActivateChild
when I can use component-less routes with canActivate
?
canActivateChild
on the rootadmin
path and that way you don't need the component-less route. The component-less method here I believe is used in the guide to demonstrate that we can even go further and group the children routes that are related in order to apply even more specialized guards on them. – John Mutuma