Angular Example - How to handle nested Http calls in a service

If there is a need to make multiple Http calls which are dependent , we need to do nested calling in Angular service. Lets head to the example below.

Requirement - Get the best theater for a given user

Step 1 : Make a Http call to /userservice to get the user location PIN code - Returns Observable<number>
Step 2 : Another Http call to /locationservice to get the best theater in the region of PIN code for given user - Returns Observable<string>

Example code for above requirement is below.

Service code

getBestTheaterInUserLocationPIN(userID: string): Observable<string> {
  return this.http.get<number>("http://host:8080/userservice/userpin" + "/" + userID).pipe(
    mergeMap((pinCode:number) => {
      return this.http.get<string>("http://host:8081/locationservice/besttheater" + "/" + pinCode).pipe(
        map((theater:string) => {
          // return modified theater name to have first letter to be capital
          return theater.charAt(0).toUpperCase() + theater.slice(1);    

Component code

this.theaterService.getBestTheaterInUserLocationPIN(userID).subscribe(theaterName => {
  console.log(theaterName);   // Output : Avlon cinemas

Step by step explanation

  1.  Component makes a service call "getBestTheaterInUserLocationPIN(userID)" to get the theater name
  2. Service getBestTheaterInUserLocationPIN() first calls service 1 ( userservice ) to fetch user location PIN
  3. service 1 returns a number
  4. now service 2 ( locationservice ) is called to fetch best theater name by PIN Code
  5. service 2 returns theater name as string
  6. mergeMap merges Observables from both the service calls and returns a single Observable of type string
  7. subscribe callback in Component gets the response as theaterName

What happens without mergeMap()

There are two Observables ( outer Observable from service 1 , inner Observable from service 2 ) in above nested service. If mergeMap() is replaced with map() , response will be of nested Observables ( Observable<Observable<string>> ) instead of flat one Observable<string> , which requires Component to subscribe in nested way.


Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>