0

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?

eko
  • 39,722
  • 10
  • 72
  • 98
Moshe
  • 2,583
  • 4
  • 27
  • 70
  • You never get an error logged in the console? Have you debugged the `IsValid` function? Is your auth service working? What does the `console.log(isValid);` reveal? – R. Richards Apr 04 '17 at 23:40
  • Console log reveals isValid is true. I got no errors, and my auth service is working – Moshe Apr 04 '17 at 23:42

1 Answers1

1

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?

Community
  • 1
  • 1
eko
  • 39,722
  • 10
  • 72
  • 98
  • I get the following error: `TS2355: A function who's declared type is not 'void' or 'any' must return a type.` – Moshe Apr 05 '17 at 14:20
  • @Moshe I've updated my answer. `isValid()`s return type should be `any` at this point – eko Apr 05 '17 at 14:32