Let's say I have two REST API endpoints as follows:
To load a lookup list (e.g. Locations): host/api/locations
to load user details: host/api/user/1
I will be displaying this information on a HTML form, which has a to load the location list. When the user details is loaded, the default selected value should be set to user's home location which is part of user details.
I know I can do this by chaining, either using subscribe method or using flatmap in RxJs. But both of them are actually for when the second API call is dependent on the response of the first. In my case, there's no dependency between the two API calls, the only glitch is that the locations should be loaded in the for the user's home location to be set as the selected value.
What is the best way to do this?
Here, rxjs forkJoin operator comes for your help. It makes sure to emit values when response from all observables have arrived. Here is a descriptin from rxjs site
One common use case for this is if you wish to issue multiple requests on page load (or some other event) and only want to take action when a response has been received for all. (detailed link)
Your implementation shall be something like this
let req1$ = this.apiService.api1(); //first observable
let req2$ = this.apiService.api2(); //second observable
forkJoin(req1$, req2$).subscribe(([response1, response2])=>{
//Your implementation shall go here.
});
Thanks.