[英]Interceptor not intercepting http requests (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);
}
}
}
有誰知道可能導致此問題的原因是什么? 提前致謝。
你用正確的方式攔截。
對於使用攔截器的人,您需要進行 2 處修改:
攔截器在使用中
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse }
from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).do(evt => {
if (evt instanceof HttpResponse) {
console.log('---> status:', evt.status);
console.log('---> filter:', req.params.get('filter'));
}
});
}
}
提供 HTTP_INTERCEPTOR
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
(...)
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
],
閱讀這篇文章了解更多詳情。 這個很不錯
如果您有一個模塊的 providers 數組,那么您必須為該模塊定義 HTTP_INTERCEPTORS ,那么只有它會攔截該模塊下的請求。
例如:
providers: [
// singleton services
PasswordVerifyService,
{ provide: HTTP_INTERCEPTORS, useClass: AppInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptorService, multi: true }
]
就我而言,我必須在同一個模塊中同時導入HTTP_INTERCEPTORS, HttpClientModule
。
就我而言,我有一個這樣的 post 方法:
this.http.post<any>(this.authUrl, JSON.stringify({username: username, password: password})).pipe(
map((response: any) => {
let token: any = response.token;
if (token) {
localStorage.setItem('currentUser', 'value' }));
return response;
} else {
return null;
}
}),
catchError((error:any) => {return observableThrowError(error.json().error || 'Server error')})
);
因為map
方法可能返回null
,所以攔截器停止攔截使用此 post 方法調用發出的請求。 不要問我為什么會這樣,但是一旦我用說response
替換null
,一切又開始工作了。
就我而言,我不知道如何,但我使用的是useValue
而不是useClass
。
在我的情況下,我不小心在我的組件中提供了服務providers : [ ApplicationService ]
,而它不應該像我使用providedIn: 'root'
定義的那樣
請確保模塊中還提供了攔截器的依賴項。 攔截器依賴服務的 ProvidedIn:'root' 對我不起作用。
就我而言,由於我正在使用模塊,因此我必須在app.module.ts中導入子模塊(AuthModule) 。 我只是想念那個。
進口:[HttpClientModule,AppRoutingModule,AuthModule]
檢查您的模塊和子模塊文件,如果您已在子模塊中導入攔截器,則將其移動到根模塊,它應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.