javascript

Angular Interceptor not Adding Header

Angular interceptor not adding header is a common problem. And, let me tell you that it is not an issue with Angular. It’s just that we don’t know a few necessary facts.

Fact #1

Please check if you have imported the HttpClientModule more than once.

We must import the HttpClientModule only once. Because of this, I prefer to import this module in a shared module and import that shared module in other modules.

This module creates an interceptor chain, which should be unique in any project.

See the below example for details.

HttpConfigInterceptor.interceptor.ts

import { Injectable } from '@angular/core';
 import {
     HttpInterceptor,
     HttpRequest,
     HttpResponse,
     HttpHandler,
     HttpEvent
 } from '@angular/common/http';
 import { Observable, throwError } from 'rxjs';
 import { map, catchError } from 'rxjs/operators';


 @Injectable()
 export class HttpConfigInterceptor implements HttpInterceptor { 
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
       if (!request.headers.has('Content-Type')) {
           request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
       }
       return next.handle(request).pipe(
           map((event: HttpEvent<any>) => {
               if (event instanceof HttpResponse) {
                   console.log('event--->>>', event);
               }
           return event;
       }));
    }
 } 

shared.module.ts

import { NgModule} from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpConfigInterceptor} from './interceptor/httpconfig.interceptor';
 @NgModule({
   imports: [
     CommonModule,
     HttpClientModule,
   ],
   exports: [
    CommonModule,
    HttpClientModule,
  ],
 providers: [
  { provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true },
  ]
 })
export class SharedModule { } 

Fact #2

Now notice that we have imported HttpClientModule in the shared module and used HttpConfigInterceptor (Custom interceptor defined in above code) as the HTTP_INTERCEPTORS provider.

Remember, we must declare HTTP_INTERCEPTORS provider in the same module where we are importing the HttpClientModule.

Many times we end up declaring the HttpClientModule in one module and HTTP_INTERCEPTORS provider in the app module.

Leave a Comment

three + five =