I am trying to build an application using Angular 9 and in my
app-routing.module.ts
const routes: Routes = [
{
path: '', canActivate:[GuestGuard], component: BlankComponent, children:[
{path:'', loadChildren: () => import('./user/user.module').then(m => m.UserModule)}
],
},
{
path: '', canActivate:[AuthGuard], component: UserComponent, children: [
{path: 'dashboard', component: DashboardComponent},
{path:'', children:[
{path: 'roles', loadChildren: () => import('./roles/roles.module').then(m => m.RolesModule), },
}
]
},
{ path: '**', redirectTo: '', pathMatch: 'full' },
];
guest-guard.ts
Used to block users who are already logged in
export class GuestGuard implements CanActivate, CanLoad {
constructor(private auth:Auth, private router:Router){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const userLoggedIn = this.auth.isLoggedIn();
if(userLoggedIn){
this.router.navigateByUrl('dashboard');
return false;
}
return true;
}
canLoad(
route: Route,
segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
const userLoggedIn = this.auth.isLoggedIn();
if(userLoggedIn){
this.router.navigateByUrl('dashboard');
return false;
}
return true;
}
}
auth-guard.ts
Allow access to users logged in (inverse of guest)
export class AuthGuard implements CanActivate, CanLoad {
constructor(private auth:Auth, private router:Router){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const userLoggedIn = this.auth.isLoggedIn();
if(!userLoggedIn){
this.router.navigateByUrl('/');
return false;
}
return true;
}
canLoad(
route: Route,
segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
const userLoggedIn = this.auth.isLoggedIn();
if(!userLoggedIn){
this.router.navigateByUrl('/');
return false;
}
return true;
}
}
Above code is working fine as expected. But when i use canLoad on the guest path, i get
Throttling navigation to prevent the browser from hanging. See <URL>.
For loggedin user path, the canLoad function is not executed (tested by using console.log)
When should canLoad be used?