I have created a simple AuthGuard that verifies a token, and returns a true/false response. The API Server (Express) and the Auth Service works fine, but there is some bug going on at if (this.isValid())
because no matter what, the user is always redirected to login.
export class AuthGuard implements CanActivate {
constructor(private router: Router,
private _authService: AuthService) { }
canActivate() {
if (this.isValid()) {
return true;
} else {
// not logged in so redirect to login page
this.router.navigate(['/login']);
return false;
}
}
isValid(): boolean {
let isValid = false;
if (localStorage.getItem('currentUser')) {
this._authService.verifyToken().subscribe(validToken => {
isValid = validToken === true;
});
}
console.log(isValid);
return isValid;
}
}
Where in my isValid
function is causing this problem?