简体   繁体   中英

HttpInterceptor not intercepting requests in Angular 10

I have a HttpInterceptor to add a JWT token from the localstorage to the headers of my http requests. I believe that all my http requests are being sent without any headers but don't understand why it isn't working.

What am I missing to make the interceptor add the headers to my requests?

My interceptor:

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)
  }
}

My service:

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);
  }

}

You have to register your interceptor eg in ApplicationModule

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

I had the same problem a while ago, and I realize that I had several modules in my application. So put the interceptor inside the module that I was trying to intercept instead of putting in the app module, and it worked!

My interceptor was like this

@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);
    }
}

and in my inner module (for instance, client.module ) was like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM