私のバックエンドは、RxJS 5 Observable(角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によって放出された配列のメンバーに変換を適用するより良い方法はありますか?
NB。私は、RxJS演算子(vs配列メソッド)が私のアイテムを変換することを望んでいます。なぜなら、各アイテムを第2の観測可能物に投影する能力が必要だからです。典型的な使用例:アイテムIDのリストのバックエンド戻り値と、これらのアイテムのすべてをバックエンドから要求する必要があります。
ありがとう、マーティン。 'concatAll()'が元の配列内の項目の順序を保持し、 'mergeAll()'は保持しないというのは正しいですか? – AngularChef
@AngularFranceあなたは配列をアンパックしているので、どちらを使うかは関係ありませんし、どちらも注文アイテムを生成します。これは、この場合ではない非同期操作で使用する場合にのみ関係します。 – martin