Search code examples
angularrxjsmergemap

Rxjs mergeMap: Concat 2 related Api Requests


I have two api requests, the second one depends on the first one. The first request gets an array of 3 facilities. After this i need to do an api request for each facility to get an image which i need. I need the uuid of the facilities. I thought this could be easy with mergeMap. But i have 2 problems and can't find a solution: inside merge map, i thought service will be one service of the array but it is the whole array. Also I need to subscribe to getImage() too and store the value inside service.image.

getNewestNursingServices() {
  return this.http.get('api/nursing-service/newest').pipe(
   mergeMap(service => this.getImage('PREVIEW', service.uuid))
  );
}
getImage(type: string, nursingService: string): Observable<Image> {
  return this.http.get<Image>('api/nursing-images/' + type + '/' + nursingService);
}

Solution

  • You can use forkJoin or concat:

    getNewestNursingServices() {
      return this.http.get('api/nursing-service/newest').pipe(
       mergeMap((service: any[]) => {
         return concat(...service.map(s => {
           return this.getImage('PREVIEW', s.uuid)
         }) 
       }) 
      );
    }