What is the difference between canLoad
and canActivate
?
export interface Route {
path?: string;
pathMatch?: string;
matcher?:
The CanLoad Guard prevents the loading of the Lazy Loaded Module. We generally use this guard when we do not want to unauthorized user to navigate to any of the routes of the module and also stop then even see the source code of the module.
The Angular provides canActivate Guard, which prevents unauthorized user from accessing the route. But it does not stop the module from being downloaded. The user can use the chrome developer console to see the source code. The CanLoad Guard prevents the module from being downloaded.
Actually,CanLoad protects a module to be loaded but once module is loaded then CanLoad guard will do nothing. Suppose we have protected a module loading using CanLoad guard for unauthenticated user. When user is logged-in then that module will be applicable to be loaded and we will be able to navigate children paths configured by that module. But when user is logged-out, still user will be able to navigate those children paths because module is already loaded. In this case if we want to protect children paths from unauthorized users, we also need to use CanActivate guard.
Use CanLoad before loading AdminModule:
{
path: 'admin',
loadChildren: 'app/admin/admin.module#AdminModule',
canLoad: [ AuthGuardService ]
},
After loading AdminModule, in AdminRouting module we can use CanActive to protect childs from unauthorized users like bellow:
{
path: '',
component: AdminComponent,
children: [
{
path: 'person-list',
component: PersonListComponent,
canActivate: [ AuthGuardService ]
}
]
}