1

I have an angular application which intercepts all outgoing requests with HTTP Interceptor to add authentication token to the request. I dont want this for the login request. So that i have been using http module for this. How can I use httpClientModule for this purpose without intercepting with the HTTP Interceptor?

2 Answers 2

4

Use HttpBackend which will dispatch the request via browser HTTP APIs directly to the backend, without going through the interceptor chain.

import { HttpBackend, HttpClient } from '@angular/common/http';

  constructor(private httpClient: HttpClient, handler: HttpBackend) {
    this.httpClient = new HttpClient(handler);
  }

Then, use this instance of httpClient for REST.

0

Since Angular 12 you can use HttpContext to handle this case. Each request can provide a context object, that is available in the interceptors to alter their behaviour.

=================

  1. Create a HttpContextToken
import { HttpContextToken } from '@angular/common/http';

export const DISABLE_AUTH_HEADER =
    new HttpContextToken<boolean>(() => false);

  1. Pass the context in your login request
import { HttpClient, HttpContext } from '@angular/common/http';

constructor(private httpClient: HttpClient) {}

login() {
  this.httpClient.post(
    'https://example.com/login',
    data,
    {
      context: new HttpContext().set(DISABLE_AUTH_HEADER, true);
    }
  ).subscribe(...);
}

  1. Read the context in your interceptor
intercept(
  httpRequest: HttpRequest<any>,
  next: HttpHandler
): Observable<HttpEvent<any>> {
  if(httpRequest.context.get(DISABLE_AUTH_HEADER) === true)
    return next.handle(httpRequest); // Continue to the next handler

  //...
}

        

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.