在我的应用程序中,我在应用程序的 UI 中使用了第 3 方 UI 小部件(我从 npm 注册表中获取它作为依赖项)。当嵌入到我的应用程序的用户界面中时,该小部件使用 axios 模块进行 GET 调用。
现在,我注意到小部件发出的 HTTP GET 调用没有被我拥有的 HTTP 拦截器拦截。来 self 的应用程序的其他 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);
});
关于javascript - HTTPInterceptor 没有拦截来自 Angular 中第 3 方小部件的 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63074721/