简体   繁体   中英

Route guard for authentication with ngrx store

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM