简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM