结合RxJS可观察量和合并,基于公共对象属性值进行映射

时间:2018-03-08 00:53:47

标签: angular rxjs

在我们的应用程序中解析(订阅)时,我在下面得到两个可观察的响应 -

obs1$.subscribe(x=>{
   Response1 = x;
});

obs2$.subscribe(y=>{
    Response2 = y;
});

Response1 = [{id: 1, qty: 0, description: "product1"},
             {id: 2, qty: 0, description: "product2"}, 
             {id: 3, qty: 0, description: "product3"}]

Response2 = [{id: 1, qty: 23, description: "product1"},
             {id: 3, qty: 10, description: "product3"}]

我正在使用RxJS Observables并且相当新。我需要合并两个响应并根据两个响应的公共ID更新数量(值应仅来自Response2)。最终的回答应该是 -

FinalResponse = [{id: 1, qty: 23, description: "product1"},
                 {id: 2, qty: 0, description: "product2"},
                 {id: 3, qty: 10, description: "product3"}]

如何使用RxJS Observables执行此操作?

1 个答案:

答案 0 :(得分:2)

您可以使用ForkJoin这里有一个如何使用它的示例,您可以根据自己的需要重塑它:

import { forkJoin } from "rxjs/observable/forkJoin";
let obs1$ = this.http.get('url 1');
let obs2$ = this.http.get('url 2');
const mergedValues = []
forkJoin([character, characterHomeworld]).subscribe(results => {
      let obs1$_result = results[0]
      let obs2$_result = results[1]
      // here you can merge with a better way...
      mergedValues = obs1$_result.map(obj => { 
         const o = obs2$_result.filter(v => v.id === obj.id);
         obj.qte = o ? o.qte : obj.qte;
         return obj
      })
});