【问题标题】:HTTPInterceptor not intercepting http requests from 3rd party widget in Angular 8 appHTTPInterceptor 未拦截来自 Angular 8 应用程序中第 3 方小部件的 http 请求
【发布时间】:2020-07-24 21:41:23
【问题描述】:

我有一个 Angular 8 应用程序,它有一个 HTTP 拦截器。在我的应用程序中,我在应用程序的 UI 中使用了第 3 方 UI 小部件(我从 npm 注册表作为依赖项获取)。该小部件嵌入到我的应用程序 UI 中时,会使用 axios 模块进行 GET 调用。现在,我注意到小部件发出的 HTTP GET 调用没有被我拥有的 HTTP 拦截器拦截。来自我的应用程序的其他 HTTP 请求被拦截,确认我的拦截器正常工作。您能否帮助我了解如何拦截小部件正在进行的 GET 调用?

下面是我的拦截器:

import { Injectable } from "@angular/core";
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Observable } from "rxjs";
import { LoaderService } from './loader.service';
import { finalize } from "rxjs/operators";


@Injectable()
export class LoaderInterceptor implements HttpInterceptor {

   

    constructor(private loaderService: LoaderService) {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (displayLoadingScreen) {

            return next.handle(request).pipe(
                finalize(() => {
                    this.activeRequests--;
                })
            )
        } else {
            return next.handle(request);
        }
    };
}

【问题讨论】:

    标签: javascript angular axios angular-http-interceptors


    【解决方案1】:

    HttpInterceptor 仅适用于 Angular 的 HttpClient(以及它的根实例,可能还有其他 HttpClients)。

    如果他们使用 Axios 进行调用,您的拦截器将无法访问,因为它没有使用您的 HttpClient

    注意:Axios 作为自己添加拦截器的方式。您可能仍然无法访问您的第 3 方库正在使用的 Axios 实例...

    这是来自 axios 文档 https://github.com/axios/axios#interceptors 的拦截器示例

    // Add a request interceptor
    axios.interceptors.request.use(function (config) {
        // Do something before request is sent
        return config;
      }, function (error) {
        // Do something with request error
        return Promise.reject(error);
      });
    
    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        return response;
      }, function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error);
      });
    

    【讨论】:

    • 我无需使用 HTTPInterceptor 就解决了这个问题(因为拦截器不起作用)。感谢回复
    • 在angular中,比如我们使用angular HttpInterceptor,我们会在app.module.ts文件的providers中注入,这样拦截器就可以正常工作了。如果我们使用 axios,我们需要如何通知 Angular 应用我们正在使用 axios?
    猜你喜欢
    • 2018-08-20
    • 1970-01-01
    • 2021-02-09
    • 2018-03-30
    • 1970-01-01
    • 2014-10-29
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多