Home > Back-end >  Angular/RxJS wait for HTTP response in inner Observable
Angular/RxJS wait for HTTP response in inner Observable

Time:07-18

I have the following case. I have a http request which returns an observable with the following data structure

[
 {
  firstName,
  secondName,
  petId
 }
]

No I have to iterate over this array and for each person I have to do a request for the pet. Not a problem so far. The problem is that I want to have the data exactly in the order how it comes from the first response.

My idea so far:

    this.personService.getPersonData().subscribe(data => {
      data.forEach(personObj =>
        this.petService.getPetData(personObj.petId)
         .subscribe(petData => 
           this.personPetData.push({...personObj, petData: petData}))
      );
    });

But when I do it like this, the order is always different.

I would very much appreciate your answers

CodePudding user response:

Try:

this.personService.getPersonData().pipe(
  switchMap(data =>
    forkJoin(data.map(personObj => 
      this.petService.getPetData(personObj.petId).pipe(map(pet => ({ ...personObj, petData: pet}))),
    )),
  ),
)
  • Related