インターセプターがHTTPリクエストをインターセプトしない(Angular 6)質問する

インターセプターがHTTPリクエストをインターセプトしない(Angular 6)質問する

私は現在、Angular 6 プロジェクトにインターセプターを追加中です。API を呼び出すには、すべての呼び出しにベアラー トークンを追加する必要があります。残念ながら、インターセプターは呼び出されていないようです。私のコード:

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>,
              next: HttpHandler): Observable<HttpEvent<any>> {

        //Retrieve accesstoken from local storage
        const accessToken = localStorage.getItem("access_token");

        //Check if accesToken exists, else send request without bearer token
        if (accessToken) {
            const cloned = req.clone({
                headers: req.headers.set("Authorization",
                    "Bearer " + accessToken)
            });

            console.log('Token added to HTTP request');

            return next.handle(cloned);
        }
        else {
            //No token; proceed request without bearer token
            console.log('No token added to HTTP request');
            return next.handle(req);
        }
    }
}

この問題の原因が何なのか知っている人はいますか? よろしくお願いします。

ベストアンサー1

私の場合、HttpClientModule異なるモジュールを複数回インポートしたため、インターセプターはサービス呼び出しに関与していませんでした。

後で、HttpClientModule一度だけインポートする必要があることがわかりました。ドキュメント参照

おすすめ記事