Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interceptor not intercepting http requests (Angular 6)

Tags:

angular

I'm in the proces of adding an interceptor to my angular 6 project. To make calls to my API, I need to add a bearer token to all calls. Unfortunately the interceptor does not seem to be called. My code:

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

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

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

        //Retrieve accesstoken from local storage
        const accessToken = localStorage.getItem("access_token");

        //Check if accesToken exists, else send request without bearer token
        if (accessToken) {
            const cloned = req.clone({
                headers: req.headers.set("Authorization",
                    "Bearer " + accessToken)
            });

            console.log('Token added to HTTP request');

            return next.handle(cloned);
        }
        else {
            //No token; proceed request without bearer token
            console.log('No token added to HTTP request');
            return next.handle(req);
        }
    }
}

Does anyone know what could be causing this issue? Thanks in advance.

like image 924
Mikey123 Avatar asked Jun 14 '18 14:06

Mikey123


People also ask

How do you give the HTTP interceptor?

Create a class AppHttpInterceptor which implements HttpInterceptor Interface. Then create an Intercept method that takes HttpRequest and HttpHandler as the argument. In the method body, you can modify the HttpRequest object. Once done, you can call the HttpHandler.


Video Answer


4 Answers

In my case interceptor wasn't getting involved for service calls because I had imported HttpClientModule multiple times, for different modules.

Later I found that HttpClientModule must be imported only once. Doc ref

Hope this helps!

like image 150
Praveen Pandey Avatar answered Oct 20 '22 17:10

Praveen Pandey


You use the right way to intercept.

For people who use interceptor, you need to do 2 modifications :

Interceptor in service

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

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {

    return next.handle(req).do(evt => {
      if (evt instanceof HttpResponse) {
        console.log('---> status:', evt.status);
        console.log('---> filter:', req.params.get('filter'));
      }
    });

  }
}

Provide HTTP_INTERCEPTOR

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
(...)
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
  ],

Read this article for more details. It's pretty good

like image 32
Pterrat Avatar answered Oct 20 '22 15:10

Pterrat


If you have a providers array for a module then you have to define the HTTP_INTERCEPTORS too for that module then only it will intercept the requests under that module.

e.g:

providers: [ 
// singleton services
PasswordVerifyService,
{ provide: HTTP_INTERCEPTORS, useClass: AppInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptorService, multi: true }
]
like image 27
Ajit Das Avatar answered Oct 20 '22 16:10

Ajit Das


In my case, I had to import both HTTP_INTERCEPTORS, HttpClientModule in same module.

like image 24
M Faisal Hameed Avatar answered Oct 20 '22 15:10

M Faisal Hameed