繁体   English   中英

HTTPInterceptor 未拦截 Angular 中来自第 3 方小部件的 http 请求

[英]HTTPInterceptor not intercepting http requests from 3rd party widget in Angular

在我的应用程序中,我在应用程序的 UI 中使用了第 3 方 UI 小部件(我从 npm 注册表作为依赖项获得)。 该小部件嵌入到我的应用程序 UI 中时,使用 axios 模块进行 GET 调用。

现在,我注意到小部件发出的 HTTP GET 调用没有被我拥有的 HTTP 拦截器拦截。 来自我的应用程序的其他 HTTP 请求被拦截,确认我的拦截器正常工作。

拦截器:

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);
        }
    };
}

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);
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM