In this tutorial you will learn how to set headers for every request in Angular using HttpInterceptor.
Table of contents
Solution
Let’s say we want to send 3 headers : Content-Type, Accept and Accept-Language. To set headers for every request in Angular, we will create a class that implements HttpInterceptor.
HttpInterceptor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http'; import {Injectable} from '@angular/core'; import {Observable} from 'rxjs'; @Injectable() export class CustomHttpInterceptorService implements HttpInterceptor { intercept(request: HttpRequest<any>, next: HttpHandler): 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); } } |
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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import {HTTP_INTERCEPTORS} from '@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_INTERCEPTORS, useClass: CustomHttpInterceptorService, multi: true}, ], bootstrap: [AppComponent] }) export class AppModule { } |
That’s it, your headers will be sent for every request.