Moshe
Moshe

Reputation: 2684

Why isn't my Auth Guard Working? Angular

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?

Upvotes: 0

Views: 759

Answers (1)

eko
eko

Reputation: 40647

You will always end up receiving false from isValid because this._authService.verifyToken() is an async operation. Async operations subscribe callback will be executed when the data arrives from your api point. Hence it will execute

console.log(isValid);
return isValid;

before the subscribe callback.

You can move the logic inside the subscribe:

isValid(): any{
    let isValid = false;
    if (localStorage.getItem('currentUser')) {
      this._authService.verifyToken().subscribe(validToken => {
        isValid = validToken === true;
        console.log(isValid);
        return isValid;
      });
    }    
}

More info on: How do I return the response from an Observable/http/async call in angular2?

Upvotes: 1

Related Questions