komratanomin
komratanomin

Reputation: 85

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:

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);
    }
  )
}

Upvotes: 3

Views: 6424

Answers (2)

Prashanth
Prashanth

Reputation: 954

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

Upvotes: 3

DeborahK
DeborahK

Reputation: 60518

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.

Upvotes: 8

Related Questions