1
votes

Let's assume I have a REST server with two possible GET requests.
One like this: /allItems and another one: /{itemId}/picture.
The first returns all stored items on my server as an array (only once), in which each one has an Id.
For each of them i would like to request their respective picture and match it with them.
Something like this:

this.http.get('/allItems').map(itemArray => {
   itemArray.forEach(item => {
       this.http.get('/' + item.id + '/picture')
                .subscribe(pic => item.pic = pic)
   return itemArray
 }
})

At the end i want to return one Observable which emits the item-array with their respective pictures mapped, so other functions can access the complete data.

Might be worth mentioning: I'm using Angular/Typescript.

3
That's it. Thank you very much! :)mortom123

3 Answers

0
votes

I understand from the comments that OP has already found the solution. For those who are wondering, this is how you can use forkJoin, which waits for the Array. forEach() loop to be completed before returning the observable values.

Here is how it could be implemented:

import { forkJoin } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

this.http.get('/allItems').pipe(
  mergeMap(itemArray => {
    const observableList = [];
    itemArray.forEach(item => {
      observableList.push(this.http.get(`/${item.id}/picture`));
    });
    return forkJoin(observableList);
  )}
).subscribe(res => {
  console.log(res);
  // handle the rest here
})
0
votes

@emkay I refactor your code. I think that it looks better. @mortom123 want to replace in object value for the key pic.

this.http.get('/allItems')
 .pipe(
  .mergeMap((itemArray) => from(itemArray))
  .mergeMap((item) => this.http.get(`/${item.id}/picture`))
   .pipe(
    map((picture) => (
      {
        ...item,
        pic: picture
      })
 ).subscribe((data) => console.log(data));
0
votes

One approach to this problem can be something like this:-

this.http.get('/allItems').pipe(
  mergeMap((itemsArray) => of(itemsArray)),
  mergeMap(item => this.http.get('/' + item.id + '/picture')
    .pipe(
      map(picture => { const a = { 'item': item, 'image': picture }; return a; })
    ),
    toArray()),
).subscribe();  ---> this will give the array of json with item and picture field.