How to call multiple http requests parallel and handle errors individually

I have 4 functions similar to the one below. Right now I'm calling them one at a time on ngOnInit() but I'm looking for a cleaner way to call all 4 functions (GET HTTP Requests) so that they show spinner... all run parallel... and then close spinner and handle any errors. This is for a project using angular 7.

 getCustomers() { return this.apiService.getCustomers() .subscribe( (data: any) => { this.partners = data; this.loading = false; }, error => { console.log(error); this.loading = false; } ); }
2

1 Answer

You need to combine all observables from your service into a single observable and then subscribe to the newly created observable. to do this you can use RxJs operator forkJoin

the fork join subscription will wait for all observables to complete and then emit the values to the subscription method -note that mean single success and single error for all since the observable will only emit once

you can also use RxJs Operator combineLatestthis will create single observable from your list of observers and emit a value every time one of the observables complete. the value will be array of all last values emmited from your observers or null in case an observer not finished. this will allow you to handle error state for each api call but will also fire the subscription event multiple times.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like