使用 Rxjs 具有不同标头的多个请求
Posted
技术标签:
【中文标题】使用 Rxjs 具有不同标头的多个请求【英文标题】:Multiple requests with different headers with Rxjs 【发布时间】:2022-01-04 02:40:25 【问题描述】:我有这个请求,当 hasProcessado == true
执行 10 个请求并发出最后一个请求时,如果它失败了,则再发出 3 个请求。
但是当我发出最后一个请求时,我需要用不同的标头通知后端
我的要求:
public getProfitability(): Observable<Profitability>
let result = this.http.get<Profitability>(this.configService.generateNewUrl(`$environment.api.newEndpoints.profitability`), headers: this.configService.concatenateHeaders())
return result
.pipe(
concatMap(res => iif(() => res.hasProcessed,
of(res),
interval(500).pipe(
take(10),
concatMap(() => result),
tap(result => console.log(result)),
)
)),
retryWhen(
error =>
error.pipe(
tap(() => console.log("error occurred getProfitability() ")),
delay(500),
take(3),
)
),
shareReplay(1),
last()
);
我想在标头pullingOk = true
中用一个参数通知后端
类似的东西:
private pullingPerfilInvestidor(): Observable<PerfilInvestidor>
let result = this.http.get<PerfilInvestidor>(this.configService.gerarUrlNovo(`$environment.api.endpointsNovos.obterPerfil`), headers: this.configService.concatenarHeaders())
return result
.pipe(
concatMap(res => iif(() => !res.hasProcessado,
of(res),
interval(500).pipe(
take(10),
concatMap(() => result),
// tap(result => console.log(result)),
)
)),
retryWhen(
error =>
error.pipe(
tap(() => console.log("error occurred ")),
delay(500),
take(3),
)
),
shareReplay(1),
last()
return this.http.get<Profitability>(this.configService.generateNewUrl(`$environment.api.newEndpoints.profitability`), headers: this.configService.paramOk()))
);
【问题讨论】:
那么问题/问题是什么? 【参考方案1】:创建一个拦截器来解决这个问题
export class PullingInterceptor implements HttpInterceptor
constructor()
public countRequest: number = 0;
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
if (request.url.includes('yourURL'))
this.countRequest = this.countRequest + 1;
if (this.countRequest == 10)
const newRequest = request.clone(
setHeaders:
'your-header': 'abc'
);
return next.handle(newRequest);
return next.handle(request);
return next.handle(request);
【讨论】:
以上是关于使用 Rxjs 具有不同标头的多个请求的主要内容,如果未能解决你的问题,请参考以下文章
Angular/RxJS 6:如何防止重复的 HTTP 请求?