簡體   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