File

src/app/auth/auth-interceptor.ts

Description

This interceptor is to transform the HTTP headers by setting the autorization token for all Auth related requests.

Index

Methods

Constructor

constructor(authService: AuthService)

This is for binding the AuthService to this component.

Parameters :
Name Type Optional Description
authService AuthService No

holds the AuthService

Methods

intercept
intercept(req: HttpRequest, next: HttpHandler)

Get the Token from AuthService by calling getToken() and add the token to the HTTP headers.

Parameters :
Name Type Optional Description
req HttpRequest<any> No

Request to wich the token should be attached.

next HttpHandler No

Next method in chain.

Returns : any

Call the next method in chain and hand over the transformed request.

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

/**
 * This interceptor is to transform the HTTP headers by setting the autorization token for all Auth related requests.
 */
@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  /**
   * This is for binding the `AuthService` to this component.
   * @param authService holds the AuthService
   */
  constructor(private authService: AuthService) {}

  /**
   * Get the Token from `AuthService` by calling `getToken()` and add the token to the HTTP headers.
   * @param req Request to wich the token should be attached.
   * @param next Next method in chain.
   * @returns Call the next method in chain and hand over the transformed request.
   */
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const authToken = this.authService.getToken();
    const authRequest = req.clone({
      headers: req.headers.set("Authorization", "Bearer " + authToken)
    });
    return next.handle(authRequest);
  }
}

results matching ""

    No results matching ""