Add Token to Requests with HTTP Interceptor
Add Token with each request

 

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpInterceptor } from '@angular/common/http';
import { AuthService } from './auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
 constructor(private authService: AuthService) {}

 intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>> {
   const token = this.authService.getToken();
   if (token) {
     const authReq = req.clone({
       headers: req.headers.set('Authorization', `Bearer ${token}`),
     });
     return next.handle(authReq);
   }
   return next.handle(req);
 }
}

 

 

App Module 
(src/app/app.module.ts):
Register your Interceptors At Module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './auth/login/login.component';
import { ProtectedComponent } from './protected/protected.component';
import { AuthInterceptor } from './auth/auth.interceptor';

 

@NgModule({
 declarations: [
   AppComponent,
   LoginComponent,
   ProtectedComponent,
 ],
 imports: [
   BrowserModule,
   FormsModule,
   HttpClientModule,
   AppRoutingModule,
 ],
 providers: [
   { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
 ],
 bootstrap: [AppComponent],
})
export class AppModule {}

 

  • provide is a provider configuration object key. The dependent token you want to value is specified.
  • @angular/common/http's HTTP_INTERCEPTORS token is built-in. This token is an HTTP interceptor multi-provider. Consider it an assortment of interceptor services.
  • UseClass is another provider configuration key. When a reliance on the HTTP_INTERCEPTORS token is requested, it tells Angular's dependency injection engine to build an instance of the provided class (AuthInterceptor).
  • AuthInterceptor - our custom interceptors. This service implements @angular/common/http's HttpInterceptor. This class's intercept() method lets you inspect and change HTTP requests and responses. Outgoing requests often include authorisation headers like the Bearer token for authentication.
  • multi: true: multi is a provider configuration boolean. it tells Angular that this provider should be added to a collection of values associated with the HTTP_INTERCEPTORS token, rather than replacing any existing providers for that token.

Related Question