CanActivate vs. CanActivateChild with component-less routes
Solution 1:
From the docs:
As we learned about guarding routes with CanActivate, we can also protect child routes with the CanActivateChild guard. The CanActivateChild guard works similarly to the CanActivate guard, but the difference is its run before each child route is activated. We protected our admin feature module from unauthorized access, but we could also protect child routes within our feature module.
Here's a practical example:
- navigating to
/admin
-
canActivate
is checked - You navigate between the children of
/admin
route, butcanActivate
isn't called because it protects/admin
-
canActivateChild
is called whenever changing between children of the route its defined on.
I hope this helps you, if still unclear, you can check specific functionality by adding guards debugging them.
Solution 2:
In real world, I feel it is redundant to use the same guard for the parent and all its children.
For a better example, suppose you have roles for admin users (Edit/View), you can add a guard for "Edit" only tabs.
RouterModule.forChild([
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard], //1 - redirect to login page if not logged in
children: [
//View Access
{
......
},
//Edit Access
{
path: '',
canActivateChild: [EditGuard], //2 - display "you don't have Edit permission to access this page"
children: [
{ path: 'crises', component: ManageCrisesComponent },
{ path: 'heroes', component: ManageHeroesComponent },
{ path: '', component: AdminDashboardComponent }
]
}
]
}
])