3

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
    Technically they all run in parallel already, except they're triggered one after another. Because it's a .subscribe() function, it doesn't stop the rest of the code execution. Are you trying to show a spinner when something does an HTTP call on your webapp? Commented Jul 19, 2021 at 20:07
  • For the error, I'd personally handle them in the service function (apiService.getCustomers() in this case). I've answered a similar question here stackoverflow.com/questions/46018259/…, 90% it still applies except for the map(), which you don't need to do if your classes match the response JSON structure. Angular has data casting support now. Commented Jul 19, 2021 at 20:12

1 Answer 1

7

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 combineLatest this 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok thanks... I will start looking into forkjoin.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.