javascript - 链二选择 rxjs store in Angular Guard

标签 javascript angular typescript rxjs ngrx

我正在尝试从 Angular Guard 中的 ngrx 存储中选择两个字段,如下所示:

@Injectable()
export class RoleGuard implements CanActivate {

  constructor(
    public router: ActivatedRouteSnapshot,
    private store: Store<AppState> ) {}

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {

    const expectedRole = route.data.Role;

    return combineLatest(
        this.store.pipe(select(isLoggedIn)),
        this.store.pipe(select(currentUser)),
      ).pipe(
          tap( ([loggedIn, user]) => 
                {
                    if ( loggedIn && !(user.role.find(expectedRole) >= 0) ) {
                        this.router.navigateByUrl('/error/403')
                    };
                }
            )
        );


  }

}

但是,我得到 Type 'boolean | [any, any]' 不可分配给类型 'boolean',这是有道理的,因为 combineLatest 返回数组中的结果。但我似乎找不到比 combineLatest 更优雅的方法,而不是嵌套两个 select observable,我在这里有什么选择?

最佳答案

canActivate 方法应该返回一个包含在 Observable 中的 boolean。根据您的代码,它返回包装在从 combineLatest 方法返回的 Observable 中的值,该方法是一个数组。您可以使用 map 运算符返回 truefalse,如下所示:

@Injectable()

export class RoleGuard implements CanActivate {

  constructor(
    public router: ActivatedRouteSnapshot,
    private store: Store<AppState> ) {}

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {

    const expectedRole = route.data.Role;

    return combineLatest(
        this.store.pipe(select(isLoggedIn)),
        this.store.pipe(select(currentUser)),
      ).pipe(
          map( ([loggedIn, user]) => 
                {
                    if ( loggedIn && !(user.role.find(expectedRole) >= 0) ) {
this.router.navigateByUrl('/error/403')
                      //I am assuming that you want to fail the guard and want your application to route to 403 page, so let’s return false
                      return false;
                    };

                  //I am assuming that you want to pass the guard of above if condition fails, so return true; bottom line is to return true/false as per your logic.
                  return true;

                }
            )

);
  }

}

希望对您有所帮助。

关于javascript - 链二选择 rxjs store in Angular Guard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57446818/

相关文章:

javascript - 在 Canvas 中查找多边形的坐标

angular - ViewEncapsulation ShadowDom 与模拟

angular - ionic 4 - ionic cordova build android --prod 不会将 Angular 环境.prod 复制到环境中

html - 如何以 Angular 解析嵌套的json

javascript - 模拟 firebase 模块后模拟 firebase auth 方法的实现

javascript - 我可以使用不依赖于选择器的自定义 jQuery 函数进行链接吗?

javascript - 我如何拦截组件以检查权限

javascript - 如何覆盖 javascript 类中的 var?

unit-testing - Angular2 单元测试 - 为什么 nativeElement 有空的 CSSStyleDeclaration

javascript - 如何在 ngFor 中实例化和使用后续数组?