HTTPInterceptor没有拦截来自Angular中第三方小部件的http请求



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

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

拦截器:

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是其自己添加拦截器的方式。您可能仍然无法访问第三方库正在使用的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);
});

最新更新