Is there a way to check if a user has access by making an API call within an authentication guard in Angular? I'm not sure how to handle the asynchronous nature of the call and return a value based on its result.
The goal is to retrieve the user ID, use it to make an API request, and then return either true or false depending on the response from the API.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from 'src/app/services/auth.service';
@Injectable({
providedIn: 'root'
})
export class TeamcheckGuard implements CanActivate {
success: boolean;
constructor(
private router: Router,
private authService: AuthService
) {}
// Checks to see if they are on a team for the current game they selected.
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
this.authService.getUserId().then(() => {
let params = {
gameId: next.params.id,
userId: this.authService.userId
};
this.authService.getApi('api/team_check', params).subscribe(
data => {
if (data !== 1) {
console.log('fail');
// They don't have a team, lets redirect
this.router.navigateByUrl('/teamlanding/' + next.params.id);
return false;
}
}
);
});
return true;
}
}