0
votes

I get two responses below for each of observable when resolved (subscriptions) in our app -

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"}]

I am using RxJS Observables and fairly new to it. I need to merge both responses and update the qty (value should be from Response2 only) based on common ids of both responses. The final response should look like -

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

How can I do this using RxJS Observables ?

1

1 Answers

2
votes

You can work with ForkJoin here is an example of how to use it, you can reshape it to your needs:

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
      })
});