我有两个可观察对象,我想等待它们的结果,这样我就可以根据另一个来过滤一个的结果。他们各自工作:
this.allValues$ = this.store.select(selectors.getAllValues)
this.myId$ = this.store.select(selectors.myId)
我可以使用异步管道将它们渲染到模板
但是我想创建一个包含过滤数组的类属性。如果是同步 JS,类似
this.filteredResults = allValues.filter(value => value.id === myId)
zip
ing 会得到值
this.filteredResults$ = zip(
this.store.select(selectors.getAllValues),
this.store.select(selectors.myId)
)
模板: 结果:{{ filteredResults$ |异步 | JSON }}
但我无法理解如何按照我的意愿进行过滤。我试过将 pipe
链接到 zip
:
.pipe(
tap((...args) => {
console.log({ args }) // only one result so no hope of dropping in `map` or `filter` here
})
)
但这具有从结果集中删除 allValues
数组的效果。 allValues
大得多,因此可能需要更长的时间,并且 zip 不再等待所有内容发出,所以我猜 pipe
不是解决方案,尽管它看起来很接近。
我怎样才能访问这两个结果集,过滤它们,并将结果放入我可以使用 filteredResults$ | 在模板中呈现的可观察对象中?异步 | json
?
最佳答案
您可以使用 concatMap
或 switchMap
。
this.filteredResults = this.store.select(selectors.myId).pipe(
concatMap(myId => {
return this.store
.select(selectors.getAllValues)
.pipe(filter(value => value.id === myId));
})
);
关于javascript - 我如何等待多个结果,然后根据接收到的数据过滤它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56351184/