简体   繁体   中英

Angular/RxJS wait for HTTP response in inner Observable

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

Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM