I have a simple function in my service:
/**
* Funtion to check if the user logged in has admin rights
*/
isAdmin(user_id: string) {
var adminTemp: boolean;
this.httpClient
.get(`${this.urk}/${user_id}`)
.subscribe((data: any) => {
if (data.includes('Admin')) {
adminTemp = true;
} else {
adminTemp = false;
}
});
return adminTemp;
}
This function is called in a canActivate
function which needs a bool value to determine if the user is an admin or not.
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if(this.loginService.isAdmin('123')){
return true;
}
else{
return this.router.parseUrl("/admin/logout");
}
}
The problem is that before the api call is made, it takes a value of undefined and marks the user as non-admin. I understand this happens because subscribe itself is an async call. I could not find any other way to figure out how to do this, as the api response has to be processed before it can be known if they are a user or not, else I would have used a simple return statement. How should I proceed?