import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
      import { Observable } from 'rxjs';
      import { tap } from 'rxjs/operators';
      export class LogInterceptor implements HttpInterceptor {
        constructor() {}
        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
          const started =;
          return next.handle(req).pipe(
            tap(event => {
              if (event instanceof HttpResponse) {
                const elapsed = - started;
                console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
      Typescript language logo
      your recipe card header background

      Angular HTTP Interceptor Logging



      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 to get the amount of time it took for that response to come back.

      Library: angular

      Shortcut: angular.http.interceptor.logging


        Add Comment

        Log in to add a comment

        Codiga - All rights reserved 2022.