Depending on the value of userRole received from the header, I need to redirect to different user pages.
angular.routing.ts
{ path: '', pathMatch: 'full', redirectTo: '/login' },
{ path: 'user', loadChildren: './home/home.module#HomeModule', canActivate: [AuthGuard], data: { roles: Role.User} },
{ path: 'admin', loadChildren: './somemodule#SomeModule', canActivate: [AuthGuard], data: { roles: Role.Admin}},
{ path: 'login', component: LoginComponent, canActivate: [RandomGuard] }
I am initially redirected to the LoginComponent. The RandomGuard calls an API to fetch the header details from the server.
random.guard.ts
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.loginService.isHeader().pipe(
map(e => {
if (e.headers.get('userRole') === 'user') {
this.router.navigate(['/user']);
} else if(e.headers.get('userRole') === 'admin') {
this.router.navigate(['/admin']);
} else {
return true;
}
}),
catchError((err) => {
this.router.navigate(['/login']);
return of(false);
})
);
}
loginservice.ts
isHeader(): Observable<boolean> {
return this.http.get(`${environment.baseUrl}home/login`,{observe: 'response'}).pipe(
map((response: any) => {
return response;
})
);
}
To receive the header value, it is necessary to subscribe to the http get call and refactor the code accordingly.