Currently, in Angular, you can restrict access to all child routes by applying a router guard to one of the parents:
export const routes: Routes = [
{
path: 'my-account',
canActivate: [IsUserLoggedIn],
children: [{
path: 'settings',
component: SettingsComponent
}, {
path: 'edit-profile',
component; EditProfileComponent
}]
}
];
This is useful to avoid having to repeat the canActivate
guard in each route. But now what happens when I want to introduce a third route under my-account
that should be publicly accessible? For example, maybe there's a publicly-accessible Help page at my-account/help
that everyone should be able to access, even when they aren't logged in:
}, {
path: 'help',
component: HelpComponent,
// Somehow make exception to canActivate guard above
}, {
Is there a clean way to do this, or is the only way to disrupt the organization of routes and apply the router guard to each child route manually, except the Help page?
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.
canActivate: It checks if the user can visit the specific route or we have to prevent access to the specific route. For this, we use the CanActivate interface. Here, the canActivate method has two arguments.
Now here if we want to prevent navigation of an unauthorized user we can use CanActivate Guard, that will do the job but also download the module. Now to control the navigation as well as prevent downloading of that module we can use CanLoad Guard.
The Angular router's navigation guards allow to grant or remove access to certain parts of the navigation. Another route guard, the CanDeactivate guard, even allows you to prevent a user from accidentally leaving a component with unsaved changes.
I personally think if the HelpComponent
route doesn't need to be protected, it will need to be in different parent route. So, it's the matter of organizing the routes.
But, in any case, you could also create a separate route for it, such as:
export const routes: Routes = [
{
path: 'my-account',
canActivate: [IsUserLoggedIn],
children: [{
path: 'settings',
component: SettingsComponent
}, {
path: 'edit-profile',
component: EditProfileComponent
}]
},
{
path: 'my-account/help',
component: HelpComponent
}
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With