【问题标题】:Angular 13: Http Interceptor not FinalizingAngular 13:Http 拦截器未完成
【发布时间】:2022-01-15 17:26:59
【问题描述】:

我有一个 HtppInterceptor,可以在我的应用程序中启动和停止进度条。这通常适用于大多数 Http 请求,但我有许多 api 调用,当这些调用发生时,HttpHandler 永远不会完成,所以进度条不会停止。我添加了几个日志点以查看哪些调用未完成:

    intercept(
    req: HttpRequest<any>,
    next: HttpHandler
): Observable<HttpEvent<any>> {
    console.log('loading', req.url, this.handleRequestsAutomatically);

// If the Auto mode is turned off, do nothing
    if (!this.handleRequestsAutomatically) {
        return next.handle(req);
    }

    this._setLoadingStatus(true, req.url);

    return next.handle(req).pipe(
        finalize(() => {
            console.log('Finished Loading', req.url);

            this._setLoadingStatus(false, req.url);
        })
    );
}

Api 调用创建以下请求:

:authority: localhost:5001
:method: GET
:path: /api/Appointments/ej?appointmentGroupId=1&year=2022&month=1&day=14
:scheme: https
accept: application/json
accept-encoding: gzip, deflate, br
accept-language: en-AU,en-GB;q=0.9,en-US;q=0.8,en;q=0.7
authorization: Bearer <token>
dnt: 1
origin: http://localhost:4200
referer: http://localhost:4200/
sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like 
Gecko) Chrome/97.0.4692.71 Safari/537.36

我最初认为 api 调用必须保持某种连接打开,但我看不到会发生这种情况,并且标头请求中没有“keep-alive”。 api调用正确返回数据,我看不到连接在两端保持打开状态。

为什么 HttpClient 调用没有完成并停止我的进度条?

【问题讨论】:

    标签: angular typescript angular-httpclient angular-http-interceptors


    【解决方案1】:

    这是一个设计错误。

    问题是在 api 库中,有另一个拦截器在标头中设置用户令牌。在该拦截器内部,正在克隆 HttpRequest 对象。

    由于第一个拦截器在等待原始请求完成,而第二个拦截器在克隆上调用请求,所以第一个请求从未完成。

    将加载指示器服务添加到第二个拦截器并从那里调用_setLoadingStatus(false, req.url) 可以解决问题。

    编辑:正如 chrisY 在下面指出的,更好的解决方案是更改导入语句的顺序,以便 LoadingHttpInterceptor 排在最后。这样它就可以从实时 HttpClient 中运行,并且不会发生错误。

    【讨论】:

    • 感谢您的信息。更改拦截器的顺序并将 LoadingInterceptor 放在最后也可能会有所帮助。
    猜你喜欢
    • 2023-03-13
    • 2017-11-07
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多