Angular HTTP Intercepter Headers

    0

    0

    Jose Romero

    Angular TypeScript Recipes

    The HeaderInterceptor intercepts HTTP requests and returns an Observable of HttpEvents. The intercept() function takes in aHttpRequest object and a next handler. The next handler will be called with the request and the headers associated with the request. The intercept() function sets the Content-Type header to be application/json. The intercept() function then creates an HTTP request clone with the headers. The clone() function creates a new HTTP request that will have the same headers as the original request. The intercept() function then returns the next handler, which will handle the authReq in the clone HTTP request.

    Library: angular

    Shortcut: angular.http.interceptor.headers

    import { Injectable } from '@angular/core';
    import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class HeaderInterceptor implements HttpInterceptor {
      constructor() {}
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const headers = req.headers
          .set('Content-Type', 'application/json');
        const authReq = req.clone({ headers });
        return next.handle(authReq);
      }
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.