I'm trying to route the user to different components after login, based on roles.
But when I route, I get an infinite loop in canActivate as route url is always empty, which should only be true the first time, second time it should be either the path "/admin" or "/user".
App-routing.module.ts
const routes : Routes = [
{ path : '' , redirectTo : '', pathMatch: 'full' , canActivate : [RedirectGuardService] },
{ path : 'admin' , component : DashboardComponent , canActivate : [AuthGuardService], data : { role : 'admin'}},
{ path : 'user' , component : UserComponent , canActivate : [AuthGuardService], data : { role : 'user'}},
];
Redirect-guard.service.ts
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean {
const role = localStorage.getItem("role");
if (role) {
alert("navigate to the right detination based on role");
this.router.navigate(['/'+ role]);
return true;
}
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
- I did not include the code for AuthGuardService as it never hits that code.
- alert("navigate to the right detination based on role"); gets displayed infinite.
- route: ActivatedRouteSnapshot is always empty: (url:'')
''
redirects to''
. Maybe that is causing the infinite loop? - joshrathke