I am currently working on a code that verifies whether the browser contains user information. If not, the browser will make an API call to retrieve the user information from the server. Only users with valid information are granted access to navigate to different pages.
My issue lies in the fact that the canactivate() function does not pause for the API call to finish. I have attempted to use Resolvers as suggested in other discussions, but unfortunately, this did not resolve the problem either.
In an attempt to address this, I implemented async-await within the code, however, this approach also proved ineffective. The canactivate() function continues executing before the getUser() function has completed. Is there a mistake in the syntax of the async-await implementation in the following code snippet?
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private refService: RefService, private userInfoService: UserInfoService) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
this.getUser();
console.info('canActivate completed');
return this.userInfoService.getUserInfo() !== null;
}
async getUser() {
if(!this.userInfoService.getUserInfo()) {
await this.refService.getTamUser().toPromise( ).then(data => {
this.userInfoService.setUserInfo(data);
});
}
}
}