问题描述
我的后端经常在RxJS 5 Observable (我使用Angular 2)中以数组的形式返回数据.
My backend frequently returns data as an array inside an RxJS 5 Observable (I'm using Angular 2).
我经常发现自己想用RxJS运算符分别处理数组项,而我使用以下代码( JSBin ):
I often find myself wanting to process the array items individually with RxJS operators and I do so with the following code (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发出的数组的成员?
Is there a better way to apply transformations to the members of an array that's emitted by an Observable?
NB.我希望RxJS运算符(相对于数组方法)转换我的项目,因为我需要能够将每个项目投影到另一个可观察的项目中.典型的用例:后端返回项ID列表,我需要从后端请求所有这些项.
NB. I want RxJS operators (vs array methods) to transform my items because I need the ability to project each item into a second observable. Typical use case: backend returns of list of item ids and I need to request all of these items from the backend.
推荐答案
您可以不带任何参数使用concatAll()
或mergeAll()
.
You can use concatAll()
or mergeAll()
without any parameter.
dataFromBackend.pipe(
tap(items => console.log(items)),
mergeAll(), // or concatAll()
)
此方法(包括mergeMap
)仅在RxJS 5中有效,因为它以相同的方式对待Observable,数组,类似数组的对象,Promises等.
This (including mergeMap
) works only in RxJS 5 because it treats Observables, arrays, array-like objects, Promises, etc. the same way.
最终您还可以:
mergeMap(val => from(val).pipe(
tap(item => console.log(item)),
map(item => item.name),
)),
toArray(),
2019年1月:已针对RxJS 6更新
Jan 2019: Updated for RxJS 6
这篇关于最好的“压平"方式RxJS Observable内部的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!