Home > Enterprise >  Return an observable array with outer response properties and inner response properties Angular
Return an observable array with outer response properties and inner response properties Angular

Time:09-02

How to make an api call and from it's response which is an array, make API calls with data from each array element and return an observable array Angular

for ex,

queryThatReturnsArray().pipe(
    map((v) => {
        anotherQuery(v.id).pipe(
            map(res => {
                return {
                    name: v.name,
                    prop2: res.prop
                }
            })  
        )
    })
)

So the final outcome has to be an observable array with each array object having certain properties from the outer API response as well as some properties from inner API response

CodePudding user response:

First make the API call and get the array, then using map, create an observable using of for each element, then run the other api call, merge the two requests using map, finally, all the apis are execute parallely to give the output inside the subscribe!

queryThatReturnsArray().pipe(
    switchMap((array) => {
        const arrayData = array.map(varr => of(varr).pipe(
            switchMap((v) => {
                return anotherQuery(v.id).pipe(
                    map((res) => ({
                        name: v.name,
                        prop2: res.prop
                    }))
                )
            })
        ))
        return forkJoin(arrayData);
    })
).subscribe(output => console.log(output))

CodePudding user response:

Map the array of values to an array of observables and pass the array of observables to a suitable combination operator e.g. forkJoin.

The original observable can be mapped to the combined observable using switchMap.

queryThatReturnsArray().pipe(
  switchMap(array => forkJoin(
      array.map(v => anotherQuery(v.id)
    )
  ))
);

CodePudding user response:

queryThatReturnsArray().pipe(
  switchMap(outerArrayResponse => forkJoin(outerArrayResponse.map(
    outerArrayElement => innerQuery(outerArrayElement.id).pipe(
      map(innerElement => {
        return {
            name: outerArrayElement.name,
            prop2: innerElement.prop
        };
      }),
    );
  ))),
).subscribe(output => console.log(output));
  • Related