Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make nested HTTP calls from a Service Class and return Observable

I need to make two dependent HTTP calls from my Service Class in Angular 5 and return an Observable so that my component can subscribe to it. So inside the Service Class function:

  • HTTP call 1 will return some data, say, of type string
  • This string will be used by HTTP call 2 as input
  • HTTP call 2 returns, let's say a string[]
  • Return type of the Service Class function will be of the type Observable<string[]>

Code that is not working (error: function must return a value):

getData(): Observable<string[]> {
  this.httpClient.get<string>('service1/getData').subscribe(
    dataFromSvc1 => {
      return this.httpClient.get<string[]>('service2/getData/' + dataFromSvc1);
    },
    err => {
      return throwError(err);
    }
  )
}
like image 842
komratanomin Avatar asked Nov 17 '25 16:11

komratanomin


2 Answers

Try switchMap, something like this (NOT TESTED or syntax checked!):

getData(): Observable<string[]> {
  return this.httpClient.get<string>('service1/getData')
    .pipe(
      switchMap(dataFromSvc1 => {
         return this.httpClient.get<string[]>('service2/getData/' + dataFromSvc1);
      }),
      catchError(this.someErrorHandler)
    );
}

The subscription then goes in the component calling this method.

Let me know if this works.

like image 95
DeborahK Avatar answered Nov 19 '25 09:11

DeborahK


mergeMap or switchMap can be used in case of nested calls to get a single Observable as response.

getData(): Observable<string[]> {
  return this.httpClient.get<string>('service1/getData').pipe(
    mergeMap( (dataFromSvc1) => {
      return this.httpClient.get<string[]>('service2/getData/' + dataFromSvc1);
    }),
    catchError( (err) => {
      // handle error scenario
    }
  )
}

Find the below article to check example code snippets for both Service and Component and step by step explanation of what happens when executed.

https://www.codeforeach.com/angular/angular-example-to-handle-nested-http-calls-in-service

like image 43
Prashanth Avatar answered Nov 19 '25 09:11

Prashanth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!