I\'m encountering an issue while trying to lazy load module according to the user profile, I defined three default paths (with empty path for each route) and each user has a
The router will only try the guard on the first route that it matches. Because of this limitation you will have to try one of two options.
The first is to implement a custom UrlMatcher that will effectively do the work of your guard and then only have it match on the module you want to load. This can be difficult if you need to make use of other services as the UrlMatcher
is just a function so you won't get any DI.
The second option is to have a generic route with path ''
that has another guard on it that performs the actions of the other three guards and then routes to the appropriate module. This sounds like a bit of a hack, however, the Angular documentation suggests doing just that in the ToH tutorial.
export class CanActivateModuleGuard implements CanActivate {
constructor(private router: Router,
private userGuard: CanActivateUserModuleGuard,
private adminGuard: CanActivateAdminModuleGuard,
private modGuard: CanActivateModeratorModuleGuard) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let canGo = [{
guard: this.adminGuard,
url: 'admin',
}, {
guard: this.userGuard,
url: 'user',
}, {
guard: this.modGuard,
url: 'moderator',
}].some((config) => {
if (config.guard.canActivate(route, state)) {
if (state.url !== `/${config.url}`) {
this.router.navigate([config.url]);
}
return true;
}
});
if (!canGo) {
this.router.navigate(['/404']);
}
return canGo;
}
}
export const routes: Routes = [
{
path: '',
canActivate: [CanActivateModuleGuard],
children: [{
path: 'user',
loadChildren: 'app/user/user.module#UserModule',
canActivate: [
CanActivateUserModuleGuard
],
},
{
path: 'admin',
loadChildren: 'app/admin/admin.module#AdminModule',
canActivate: [
CanActivateAdminModuleGuard
]
},
{
path: 'moderator',
loadChildren: 'app/moderator/moderator.module#ModeratorModule',
canActivate: [
CanActivateModeratorModuleGuard
]
}],
},
{
path: '404',
component: NotFoundComponent
}
];