Search code examples
angularobservableguardcanactivate

Guard always redirects to the default route


I have a guard that checks a user's session. I am creating an observable from a promise and returning that observable.

Unfortunately the router always redirects me to homepage on refresh. I guess it has to do with the observable as when I simply navigate, it enters the if and returns the 'Observalbe.of(true)', which works.

@Injectable()
export default class SessionGuard implements CanActivate {

  constructor(private authService: AuthService) {}

  public canActivate(): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.hasSessionChecked) {
      return Observable.of(true).take(1);
    }

    const obs = Observable.fromPromise(this.authService.getSession());
    return obs.map((session) => {
      this.authService.setUserSession(session);
      return true;
    }).take(1);
  }
}

I have tried replacing the observable with a 'return true' and everything works as expected.

Any ideas? Thanks!


Solution

  • It doesn't work because canActivate is supposed to return a boolean.

    Why would you want to use an Observable ?