我的後端在RxJS 5 Observable(我正在使用Angular 2)中經常返回數據作爲數組。RxJS內部數組「變平」的最佳方法Observable
我經常發現自己想要過程中的數組項單獨與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操作符(vs數組方法)能夠轉換我的項目,因爲我需要能夠將每個項目投影到第二個可觀察項中。典型用例:項目id的列表後端返回,我需要從後端請求所有這些項目。
謝謝,馬丁。 concatAll()會保留原始數組中項目的順序並且「mergeAll()」不會保持正確? – AngularChef
@AngularFrance由於您要解包一個數組,因此您使用哪一個都不重要,並且都會生成訂購商品。這僅在與異步操作一起使用時纔有用,這不是這種情況。 – martin