【问题标题】:Combining RxJS observables and merge, map based on common object property values结合 RxJS observables 和 merge,基于公共对象属性值映射
【发布时间】:2018-03-08 00:53:47
【问题描述】:

在我们的应用程序中解决(订阅)时,对于每个可观察到的,我都会在下面得到两个响应 -

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 做到这一点?

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    您可以使用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
          })
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-11
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2023-02-13
      相关资源
      最近更新 更多