Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interceptor not intercepting http POST requests (Angular 6)

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';
like image 452
Nibin Baby Avatar asked Nov 28 '22 13:11

Nibin Baby


1 Answers

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

like image 52
Nibin Baby Avatar answered Dec 18 '22 21:12

Nibin Baby