Angular HttpInterceptor for Headers

    0

    0

    lucycodes42

    Angular snippets for TypeScript

    The HeaderInterceptor helps intercept HTTP requests and responses. It initializes an HttpRequest with the headers of the request and a clone of the headers. It returns an Observable that is emitted when the handle method is called on the next HttpHandler .

    The handle method takes an HttpHandler as a parameter. The handler is executed when the Observable is emitted by the HeaderInterceptor . The handler can access the req object, which contains the HttpRequest that was intercepted. The authReq object is a copy of the headers of the request that was intercepted.

    Library: angular

    Shortcut: a_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.