[英]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.