How to send the token in header angular

To perform the sending token in angular we need to use the interceptor.

So, if we make any HTTP call that interceptor will fire.

Step 1) Create one .ts file named MyInterCeptor.ts file and placed the below code.

import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpEvent,
  HttpResponse,
  HttpRequest,
  HttpHandler,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { Security } from './security.token';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  constructor(public security: Security) {}
  intercept(
    httpRequest: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    httpRequest = httpRequest.clone({
      setHeaders: {
        Authorization: `Bearer${this.security.token}`,
      },
    });

    return next.handle(httpRequest);
  }
}

Step 2) Open module.ts file

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
 providers: [
    Security,
    MyAuthGuard,
    Config,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MyInterceptor,
      multi: true,
    },
  ],

Multivalue means, In future you can change the class if you have requirement.

Leave a Comment