I have created an angular interceptor implementing the httpinterceptor. It is working fine for the http GET requests. But failing for POST requests.
My interceptor code is as below.
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest,         HttpHeaders,HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor() { console.log('enter constructor');
   }
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    console.log('entered interceptor')
    const token = localStorage.getItem('sessiontoken') != null ?     localStorage.getItem('sessiontoken') : 'notoken';
    const authReq = req.clone({ headers:     req.headers.set("Authorization", token) });
    return next.handle(authReq);
  }
}
The module is added with provider.
providers: [
{
  provide: HTTP_INTERCEPTORS,
  useValue: { disableClose: true, minWidth: 400, hasBackdrop: true },
  useClass: MyHttpInterceptor,
  multi: true
}
]
in the component I have imported the httpClient and used this.http.post
import { HttpClient } from '@angular/common/http';
                I found the answer, I imported the HttpClientModule to all the sub component's module. It is supposed to be imported in app.module.ts only. Once I removed all the HttpClientModule from every files, the issues was solved , successfully binding the headers to every requests. (Dont remember why I actually imported it unnecessarily, some tutorial copy mistake)
Thanks everyone, cheers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With