【发布时间】:2020-09-01 18:59:58
【问题描述】:
我有一组路由,我试图根据服务是否说用户有权限来过滤这些路由。我尝试了各种组合和转换运算符,但没有成功mergeMap, concatMap, concatAll, mergeAll。问题是 hasRoutePermission 返回一个从端点返回布尔值的 observable。提前致谢。
const exampleRoutes = [{
model: 'ExampleModel'
}, {
model: 'ExampleModel'
}, {
model: 'ExampleModel'
}, {
model: 'ExampleModel'
}];
filterRoutes(routes): Observable <[]> {
const hasRoutePermission = (route: IRouteData): Observable <boolean> =>
this.examplePermissionService.hasRoutePermission(route);
return of(items)
.pipe(
filter(item => hasRoutePermission(item))// Problem is here
)
}
我正在使用异步管道订阅模板中的过滤列表。
【问题讨论】:
-
这里很难理解,
exampleRoutes没有被使用。你能做一个stackblitz吗? -
您对 items 和 item 的使用让我觉得您还没有理解过滤器的工作原理,并且您将 rxjs 运算符过滤器与数组过滤器方法混淆了。如果 observable 发出数组,则 filter 对整个数组进行操作,而不是数组的单个项。
-
@Phix 使用 stackblitz 更新,尽可能接近复制。
-
@IngoBürk 请帮我理解 :)
-
@alphapilgrim 我建议你稍微阅读一下 observables。你的例子让我想到了两个直接的问题。 1) 您将 this.filterRoutes 的结果分配给 this.routeItems - 此方法的返回类型是 Observable,尤其是不是数组。 2)您似乎试图纯粹同步地处理这个问题,而这不是 Observables 所做的 - 相反,它们只是在订阅时才执行延迟(如下面的答案所示)。在 subscribe 方法中,您将 routeItems 设置为结果,而不是像现在这样从函数中分配。