简体   繁体   English

使用Ngrx存储进行身份验证的路由防护

[英]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. 我正在尝试创建AuthGuard以检查用户是否可以访问路由,否则,将重定向到登录视图。 I want to return an Observable<Boolean|UrlTree> from the canActivate method. 我想从canActivate方法返回一个Observable<Boolean|UrlTree> 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. 但是,我不太确定如何/在何处可以从可观察对象发出UrlTree重定向到/login ,这是因为我不熟悉整个事情,尤其是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 简单,应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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