Angular HTTP Interceptor Logging

    0

    0

    Jose Romero

    Angular TypeScript Recipes

    The @Injectable() annotation tells the compiler that this class is an injectable interface. This means that any class that wants to use the LogInterceptor's functionality must implement the LogInterceptor interface.

    The LogInterceptor's constructor() sets up the interceptor. The intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> function looks for any requests that match the given req.urlWithParams . Once it finds a request, the function evaluates the tap function. This function takes an event parameter, which is an instance of HttpResponse .

    The tap function logs a message to the console every time the event is fired. The event parameter's instanceof HttpResponse checks to see if the event is a response, and if it is, the elapsed property is multiplied by Date.now() to get the amount of time it took for that response to come back.

    Library: angular

    Shortcut: angular.http.interceptor.logging

    import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
    import { Observable } from 'rxjs';
    import { tap } from 'rxjs/operators';
    
    @Injectable()
    export class LogInterceptor implements HttpInterceptor {
      constructor() {}
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started = Date.now();
        return next.handle(req).pipe(
          tap(event => {
            if (event instanceof HttpResponse) {
              const elapsed = Date.now() - started;
              console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
            }
          })
        );
      }
    }
    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.