Monday 29 January 2018

HTTP Interceptors In Angular

Sending HTTP Headers to every request in Angular

Let’s say we want to send 3 headers in http request : Content-Type, Accept and Accept-Language. To set headers for every request in Angular, we will create a class that implements HttpInterceptor.


HttpInterceptor
import {HttpEventHttpHandlerHttpInterceptorHttpRequest
   from '@angular/common/http';
import {Injectablefrom '@angular/core';
import {Observablefrom 'rxjs';

@Injectable()
export class CustomHttpInterceptorService implements HttpInterceptor {

  intercept(requestHttpRequest<any>, nextHttpHandler): Observable<HttpEvent<any>>
{
    request = request.clone({
        headers: request.headers.set('Content-Type''application/json')
    });

    if (!request.headers.has('Accept')) {
      request = request.clone({
          headers: request.headers.set('Accept''application/json')
        });
    }

    request = request.clone({
headers: request.headers.set('Accept-Language''fr-FR')
});

    return next.handle(request);
  }
}

For Accept header, the value is only set if the caller doesn’t set it.

Adding user token to the request:
const userToken = 'secure-user-token';
request = request.clone({
    headers: request.headers.set('Authorization''Bearer ${userToken}')
});


Adding the interceptor to app.module.ts
Once the interceptor is created, we need to declare it in providers of our app.module.ts like below :

import {HTTP_INTERCEPTORSfrom '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    {
     provide: HTTP_INTERCEPTORSuseClass: CustomHttpInterceptorServicemulti: true
    },
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

That’s it, your headers will be sent for every request.

2 comments:

  1. Hi There,

    Gratitude for putting up this prolific article! You truly make everything a cake walk. Genuinely good stuff, saving time and energy.

    How to clear the cache memory or disable the cache option in browser programmatically using angularjs and javascript without using session or timestamp.

    Super likes !!! for this amazing post. I thinks everyone should bookmark this.

    Many Thanks,
    Irene Hynes

    ReplyDelete

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives