【发布时间】:2017-07-17 21:16:43
【问题描述】:
我的后端经常将数据作为一个 RxJS 5 Observable 中的数组返回(我使用的是 Angular 2)。
我经常发现自己想使用 RxJS 操作符单独处理数组项,我使用以下代码 (JSBin):
const dataFromBackend = Rx.Observable.of([
{ name: 'item1', active: true },
{ name: 'item2', active: false },
{ name: 'item3', active: true }
]);
dataFromBackend
// At this point, the obs emits a SINGLE array of items
.do(items => console.log(items))
// I flatten the array so that the obs emits each item INDIVIDUALLY
.mergeMap(val => val)
// At this point, the obs emits each item individually
.do(item => console.log(item))
// I can keep transforming each item using RxJS operators.
// Most likely, I will project the item into another obs with mergeMap()
.map(item => item.name)
// When I'm done transforming the items, I gather them in a single array again
.toArray()
.subscribe();
mergeMap(val => val) 行感觉不是很地道。
有没有更好的方法将转换应用于由 Observable 发出的数组成员?
注意。我希望 RxJS 运算符(相对于数组方法)来转换我的项目,因为我需要能够将每个项目投影到第二个 observable 中。典型用例:项目ID列表的后端返回,我需要从后端请求所有这些项目。
【问题讨论】:
-
不知道为什么。但是调用任何 flatAll 运算符,如 mergeAll 或 concatAll (反正同步无关紧要)。将作为可观察值返回每个值。