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
For Accept header, the value is only set if the caller doesn’t set it.
Adding user token to the 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 :
That’s it, your headers will be sent for every request.
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 {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 user token to the request:
const userToken = 'secure-user-token';
request = request.clone({
headers: request.headers.set('Authorization', 'Bearer ${userToken}')
});
Once the interceptor is created, we need to declare it in providers of our app.module.ts like below :
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.
Hi There,
ReplyDeleteGratitude 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
Great Article
ReplyDeleteB.Tech Final Year Projects for CSE in Angularjs
Project Centers in Chennai
JavaScript Training in Chennai
JavaScript Training in Chennai