简体   繁体   English

NestJS HttpService 同时调用多个端点

[英]NestJS HttpService Call Multiple Endpoints Simultaneously

I am using NestJS HttpModule to make GET request for one end point.我正在使用 NestJS HttpModule为一个端点发出 GET 请求。 The code is somewhat like this:代码有点像这样:

@Injectable
export class AnimalService {
  constructor(private httpService: HttpService){}
  
  getAnimalData(variant: string): Observable<AxiosResponse<Animal>> {
    return this.httpService
      .get(`http://animal.test/${variant}`)
      .pipe(map((response) => response.data));
  }
}

And now I want to create a method which calls multiple endpoints simultaneously.现在我想创建一个同时调用多个端点的方法。

getAllAnimalsData() {
  // const variants = ['birds', 'cats', 'dogs'];
  // call 
  //   http://animal.test/birds
  //   http://animal.test/cats
  //   http://animal.test/dogs
  // simultaneously
  // and process the response data
}

How can I achieve this using NestJS HttpModule ?如何使用 NestJS HttpModule实现这一点? How can I process every result?我如何处理每个结果? How can I handle if there is a partial error (eg 1 of 3 request has an error)?如果出现部分错误(例如 3 个请求中的 1 个有错误),我该如何处理?

If you want to make multiple http requests simultaneously you can use the RxJS forkJoin operator.如果你想同时发出多个 http 请求,你可以使用 RxJS forkJoin操作符。 I also added a catchError to each Observable so that any errors will be passed to the subscribe callback.我还为每个 Observable 添加了一个catchError以便任何错误都将传递给订阅回调。 The subscribe callback triggers when all Observables are finished.当所有 Observable 完成时,订阅回调会触发。

getAllAnimalsData() {
  const variants = ['birds', 'cats', 'dogs'];
  
  forkJoin(
    variants.map(v => 
      getAnimalData(v).pipe(catchError(e => of(e)))
    )
  )
  .subscribe(([r1, r2, r3]) => /* ... */)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 NestJs 异步 httpService 调用 - NestJs async httpService call RxJS:使用 NestJS HttpService 对分页 API 的并行 http 调用 - RxJS: Parallel http call to paginated API using NestJS HttpService NestJS HttpService All Method API 使用Interceptor时调用不起作用 - NestJS HttpService All Method API Call is not working when Interceptor is used Microsoft Cognitive Services的多个端点 - Multiple endpoints of Microsoft Cognitive Services simultaneously NestJS:记录HttpService调用中的请求/响应吗? - NestJS: Logging the request/response from HttpService calls? 如何使用 nestjs httpservice (axios) 获取嵌套的 api 数据 - how to get nested api data using nestjs httpservice (axios) Nestjs HttpService 错误处理与 AxiosRequestConfig 的 validateStatus function - Nestjs HttpService error handling with AxiosRequestConfig's validateStatus function 如何同时调用两个不同的REST api端点,并在我的应用程序的一个端点上显示来自这两个端点的数据? - How do I call two different REST api endpoints simultaneously and display the data from both on one endpoint of my app? 在 NestJS 上使用“useGlobalGuards”时排除端点 - Exclude endpoints when using 'useGlobalGuards' on NestJS NestJS 中相同 controller(路由别名)的两个端点 - Two endpoints for same controller (route aliases) in NestJS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM