'Interceptor not intercepting http requests (Angular 6)

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.



Solution 1:[1]

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!

Solution 2:[2]

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 }
]

Solution 3:[3]

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

Solution 4:[4]

In my case i had a post method like this:

this.http.post<any>(this.authUrl, JSON.stringify({username: username, password: password})).pipe(
      map((response: any) => {
            let token: any = response.token;
            if (token) {
                localStorage.setItem('currentUser', 'value' }));                
                return response; 
            } else {
                return null;
            }
        }),
        catchError((error:any) => {return observableThrowError(error.json().error || 'Server error')})
      );

Because the map method could return null the interceptor stopped intercepting the requests made with this post method call. Don't ask me why this is so, but as soon as i replace null with say response everything started working again.

Solution 5:[5]

In my case, I don't know how but I was using useValue instead of useClass.

Solution 6:[6]

In my case I accidentally had my service proivded providers : [ ApplicationService ] in my component when it wasn't supposed to be as I had it defined using providedIn: 'root'

Solution 7:[7]

In my case, since I am working with modules, I had to import the child module (AuthModule) in app.module.ts. I was just missing that.

imports: [ HttpClientModule, AppRoutingModule, AuthModule ]

Solution 8:[8]

Check your module & sub-module files, If you have imported the interceptor in a sub-module, then move it to the root module and it should work.

Solution 9:[9]

Please ensure that dependencies for the interceptor are also provided in the module. ProvidedIn:'root' for the interceptor dependency services did not work for me.

Solution 10:[10]

Tried with QuickStart Image and DockerHub Registry as well getting the same result.

enter image description here enter image description here

This error indicates that due to heavy load in the region in which you are attempting to deploy, the resources specified for your container can't be allocated at that time. Use one or more of the following mitigation steps to help resolve your issue.

1.Deploy to a different Azure region

2.Deploy at a later time

3.You can also reach out to support for details information.

Refernce : https://docs.microsoft.com/en-us/answers/questions/394616/trying-to-re-deploy-a-container-instance-but-error.html