Angular HttpClient Response Interceptor

When you want to log all your incoming and outgoing traffic in your application to the console of your browser when you are not in the production enviroment

reponse.interceptor.ts

import { HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
/**
 * Logs the reponse to the console when not in production
 */
export class LogResponseInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req)
            .pipe(
                tap(event => {
                    if (!environment.production) {
                        switch (event.type) {
                            case HttpEventType.Sent:
                                console.groupCollapsed(`Sent data to      : ${req.url}`);
                                console.log(`Method: ${req.method})`);
                                console.log('Parameters', req.params);
                                console.log(req.body);
                                console.groupEnd();
                                break;
                            case HttpEventType.Response:
                                console.groupCollapsed(`Received data from: ${req.url}`);
                                console.log(`Status: ${event.status} - ${event.statusText}`);
                                if (event.body) {
                                    console.log(event.body);
                                }
                                console.groupEnd();
                                break;
                            default:
                                console.log('Event Not cased...', event.type);
                                break;
                        }
                    }
                })
            );

    }
}

Registration of the Interceptor

app.module.ts

import { CommonModule } from '@angular/common';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { LogResponseInterceptor } from './shared/interceptors/response.interceptor';

@NgModule({
    imports: [
        HttpClientModule,
    ],
    declarations: [AppComponent],
    providers: [
             { provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true },
    ], bootstrap: [AppComponent]
})

Leave a Reply