2

I am trying to create an AuthGuard to check if an user can access a route, else, redirect to login view. I want to return an Observable<Boolean|UrlTree> from the canActivate method. Here is what I have so far.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    return this.store$.select(appState => appState.auth.authUser)
    .pipe(map(authUser => Boolean(authUser)));
}

However, I am not exactly sure how/where I can emit out an UrlTree from the observable to redirect to /login, since I am new to this whole thing, specially rxjs. Thanks in advance for any help.

Victor Mukherjee
  • 10,487
  • 16
  • 54
  • 97

1 Answers1

5

Maybe just

  canActivate(): Observable<boolean> {
    return this.store$.select(appState => appState.auth.authUser)
      .pipe(map(authUser => {
        if (!authUser) {
          this._router.navigate(['route-to-your-login-page'])
        }
        return authUser;
      }))
  }

Simple and should work

web.dev
  • 349
  • 1
  • 6