0

I would like to do sequential HTTP calls and merge the responses into one and unique observable.

Problem is: the way I am doing it seems to be wrong. Indeed, I would like to merge the data from the second request into the first one, but the way I did it seems to replace the result of the first one by the result of the seconde one.

Here it is the first request called:

[{vehicule_id:123, statistics:{speed:60,rotation:38}},...]

The second one:

[{vehicule_id:123, name:"name",description:"description},...]

And the result I would like to get:

[{vehicule_id:123, statistics:{speed:60,rotation:38}, name:"name",description:"description},...]

Important thing to know: the second request needs a vehicule_id provided in the response of the first one. With my code, the response of the second call replace the result of the first one instead of merging them.

Here it is my code:

getUserVehiculesInfo(user_id: number, language: string): void {
this._data.getUserVehiculesInfo(user_id, language)
  .pipe(
    map(res => res.data[user_id]),
    switchMap(vehicules => forkJoin(vehicules.map(vehicule => this._data.getVehiculesInfo(tank.vehicule_id, language)))),
    tap(console.log)
  )
  .subscribe();
}
Synops
  • 122
  • 3
  • 11

1 Answers1

1

Once you have the vehiculesInfo (the result of the forkJoin, you simply need to combine them with the vehicules:

switchMap(
  vehicules => forkJoin(...).pipe(
    map(infos => combineVehiculesAndInfos(vehicules, infos))
  )
)
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Is there a common way to do it ? Like a rxjs method ? Or do I have to create mine ? – Synops Dec 08 '19 at 09:47
  • You have to create yours. This has nothing todo with RxJS: you have two arrays both containing partial vehiclule information, and you need to combine them. This is business logic. – JB Nizet Dec 08 '19 at 09:48