【问题标题】:HttpInterceptor not intercepting requests in Angular 10HttpInterceptor 不拦截 Angular 10 中的请求
【发布时间】:2021-02-09 19:49:00
【问题描述】:

我有一个 HttpInterceptor 可以将本地存储中的 JWT 令牌添加到我的 http 请求的标头中。我相信我所有的 http 请求都是在没有任何标头的情况下发送的,但不明白为什么它不起作用。

让拦截器将标头添加到我的请求中我缺少什么?

我的拦截器:

import { Injectable, Injector } from '@angular/core';
import {HttpInterceptor} from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})

export class TokenInterceptorService implements HttpInterceptor {

  constructor(private injector: Injector) { }

  intercept(req, next) {
    let tokenizedReq = req.clone({
      setHeaders: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    return next.handle(tokenizedReq)
  }
}

我的服务:

import { baseUrl } from "../environments/environment";
import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";
@Injectable({
  providedIn: 'root'
})
export class AccountService {

  constructor(private http:HttpClient) { }

  getUser(data):Observable<any>{
    return this.http.post(`${baseUrl}/useraccount/user`, data);
  }

}

【问题讨论】:

  • 您是否已将其包含在您的应用模块文件中?
  • @illusion 是的,就像在 Antoniossss 的回答中一样
  • 成功了吗?
  • 不,它没有:(

标签: angular angular-http-interceptors httpinterceptor


【解决方案1】:

前段时间我遇到了同样的问题,我意识到我的应用程序中有几个模块。所以将拦截器放在我试图拦截的模块中,而不是放在 app 模块中,它起作用了!

我的拦截器是这样的

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
            setHeaders: {
                "Content-Type": "application/json; charset=utf-8",
                Accept: "application/json",
                Authorization: `Bearer ${AuthService.getAccessTokenFromStorage()}`,
            },
        });

        return next.handle(req);
    }
}

在我的内部模块中(例如,client.module)是这样的

...
providers: [{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }],
...

【讨论】:

    【解决方案2】:

    你必须注册你的拦截器,例如ApplicationModule

    @NgModule({
      imports: [
        HttpClientModule
      ],
      exports: [],
      providers: [
        {provide: HTTP_INTERCEPTORS, useClass: YourInterceptorClass, multi: true},
      ]
    })
    

    【讨论】:

      猜你喜欢
      • 2018-08-20
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-01
      • 2018-01-04
      • 1970-01-01
      相关资源
      最近更新 更多