In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to finish making an HTTP request to fetch user information from the API before checking the role of the user. This results in the application breaking as the user object is undefined. I am seeking a solution to ensure that the second guard waits for the first one to finish.
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard, AdminGuard]
},
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private http: HttpClient) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.http.get('https://jsonplaceholder.typicode.com/users').map(res => {
console.log('Auth Guard.');
console.log(res);
this.authService.user = {role: 'admin'};
return true;
});
return false;
}
}
@Injectable()
export class AdminGuard implements CanActivate {
constructor(private authService: AuthService) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
console.log('Admin Guard.');
console.log(this.authService.user);
if (this.authService.user.role === 'admin') {
return true;
}
return false;
}
}
Here is a plnker link - http://plnkr.co/edit/EqgruNjogTJvsC1Zt5EN?p=preview