your recipe card header background

    Angular HttpInterceptor for Logging

    0

    0

    lucycodes42

    Angular snippets for TypeScript

    To intercept a request, we need to provide the interceptor with a handler and a next. The handler will be invoked for every request that passes through the interceptor and the next provides the hook into the routing system.

    We then pipe the incoming request into our tap function, which takes an Observable as its input and returns an Observable that emits events of the same type as the input Observable. In our case, that's HttpEvents.

    The tap function will keep track of the current time and if the event that it's receiving is an HttpEvent of type HttpResponse, it will also print out the elapsed time for the request.

    Library: angular

    Shortcut: a_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
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.