7

I have following pseudocode

objects = [obj1, obj2, obj3]    
for obj in objects {
user: http.get(obj1.user_id)
product: http.get(obj1.product_id)
}.subscribe(results => {

do something with results

})

What I want here is that, I loop through an array of objects and for each object get related user and product and then subscribe to do something with the user and product. How can I do that?

StaticName
  • 239
  • 1
  • 2
  • 10
  • you can try to check this info about with observables: https://stackoverflow.com/questions/35268482/chaining-rxjs-observables-from-http-data-in-angular2-with-typescript or you can check this info about promises: https://javascript.info/promise-chaining – crizcl Feb 24 '21 at 13:11

2 Answers2

10

You could use RxJS forkJoin along with Array#map to trigger multiple observables in parallel.

const objects = [obj1, obj2, obj3];

forkJoin(
  objects.map(obj =>           // <-- `Array#map` function
    forkJoin({
      user: http.get(obj.user_id)
      product: http.get(obj.product_id)
    })
  )
).subscribe({
  next: (res) => {
    console.log(res);
    // use `res`
  },
  error: (err) => {}
});


/*
output in subscription: 
[
  { 
    user: result from `http.get(obj1.user_id)`,
    product: result from `http.get(obj1.product_id)`,
  },
  { 
    user: result from `http.get(obj2.user_id)`,
    product: result from `http.get(obj2.product_id)`,
  },
  { 
    user: result from `http.get(obj3.user_id)`,
    product: result from `http.get(obj3.product_id)`,
  }
]
*/
ruth
  • 29,535
  • 4
  • 30
  • 57
1

You could use the zip() operator to combine your requests and execute some code once every request has finished:

const sourceOne = http.get(obj1.product_id);
const sourceTwo = http.get(obj2.product_id);

zip(sourceOne, sourceTwo).subscribe(val => {
    // do something
});
DonJuwe
  • 4,477
  • 3
  • 34
  • 59