Your Vision Our Goal
+91 8888860970 info@upstacksolutions.com

Adding HTTP headers to every request angular

When you want to attach a specific header e.g authorization token to every request, the concept of Angular Interceptors is helpful

Here is the demo to add(inject) the authorization token in every request header.

Create a .ts file and add this code to it.

import { Injectable } from ‘@angular/core’;
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from ‘@angular/common/http’;
import { Observable } from ‘rxjs’;

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

intercept(req: HttpRequest, next: HttpHandler): Observable> {
const userToken = ‘secure-user-token’;
const modifiedReq = req.clone({
headers: req.headers.set(‘Authorization’, Bearer ${userToken}),
});
return next.handle(modifiedReq);
}
}

HTTP interceptor is a special kind of service that automatically copies the content into the header and modifies the request.

The intercept() method will make a copy of the original request, modify it, and will pass it along with the new request.
The authorization token is obtained and is then set in the header.

After this the interceptor service needs to be registered, so that angular is aware of it.
The registration is done in the app.module.ts in ngModule under the providers section.

The registration is done as follows:

@NgModule({
// …
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
],
})
export class AppModule { }

That’s it!!!
Now every request that will be sent by the app in the future will contain the modified header with authorization token with it.

Similarly any data can be injected in header

Leave a Reply

Your email address will not be published. Required fields are marked *