如何使用 HTTP 拦截器设置自定义请求标头

问题描述 投票:0回答:1

我正在尝试为通过重试机制的请求添加自定义请求标头。我有一个拦截器,当前可以过滤任何专门超时的请求,同时还记录错误详细信息。

我不确定的是,在重试期间我在哪里设置标题。我知道我目前的

req.clone
是不正确的,但我无法弄清楚如何同时访问请求和错误。

intercept(req: HttpRequest<any>, next: HttpHandler) {
return next.handle(req).pipe(
    timeout(30000),
    retryWhen((err) =>
        err.pipe(
            filter((error) => !(error instanceof ProgressEvent)),
            tap((error) => {
                // We'll keep track of the number of retries

                if (count > RETRY_COUNT) {
                    // abort retry
                } else {
                    // retry and set a custom header specifically to each of the retried requests

                    // This doesn't work since we are not changing the source observable and I don't think we even have access to the original req here.
                    const newReq = req.clone({
                        headers: req.headers.set('X-Retry-Count', count.toString())
                    })
                }
            }),
            delay(2000)
        )
    ),
    catchError((error) => {
        // Log the error...
    })
);}
angular rxjs
1个回答
0
投票

尝试在创建 newReq 后添加这两条指令:

const newReq = req.clone({ headers: req.headers.set('X-Retry-Count', count.toString()) })
next.handle(newReq).subscribe({ complete: () => count ++ }); // retry running and count incrementation
© www.soinside.com 2019 - 2024. All rights reserved.