Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 HTTP Interceptor is not working

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

like image 357
Mysterious Coder Avatar asked Mar 13 '19 05:03

Mysterious Coder


3 Answers

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.

like image 124
BruneX Avatar answered Oct 18 '22 03:10

BruneX


Add imports: [BrowserModule, HttpClientModule] in @NgModule.

like image 41
Abhinn Ankit Avatar answered Oct 18 '22 02:10

Abhinn Ankit


Authorization is a special header, you need to add withCredentials: true to the request to add it.

        request = request.clone({
            setHeaders: {
                'Authorization': `${currentUserToken}`
            },
            withCredentials: true
        });
like image 1
Jak Avatar answered Oct 18 '22 01:10

Jak