Angular 7 HTTP Interceptor is not working

Mysterious Coder picture Mysterious Coder · Mar 13, 2019 · Viewed 8.2k times · Source

I am new to Angular and I am trying to implement api call which send token in header on all api so I am using Interceptor.

I am not able to set header in request.

jwt.interceptor.ts

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

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor() { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        let currentUser = localStorage.getItem('useremail')
        let currentUserToken = localStorage.getItem('token')
        if (currentUser && currentUserToken) {
            request = request.clone({
                setHeaders: {
                    'Authorization': `${currentUserToken}`
                }
            });
        }
        // console.log("Request", request)
        return next.handle(request);
    }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppUserListingComponent } from './app-user-listing/app-user-listing.component';
import { JwtInterceptor } from './jwt.interceptor';

@NgModule({
  providers: [ { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true } ],
  bootstrap: [AppComponent]
})
export class AppModule { }

user-listing.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class UserListingService {
  apiUrl = "URL";
  constructor(
    private http: HttpClient
  ) { }

  fetchAllUsers() {
    return this.http.get(`${this.apiUrl}/fetchAdminsUsers`)
  }

}

What is the reason my code is not working ?

Thanks in advance

Answer

BruneX picture BruneX · Aug 30, 2019

In your app.module.ts code there's no import: [HttpClientModule] Do you have imported the HttpClientModule?

I'm experiencing a similar issue with angular 8.x http interceptor is not working OK.