How to monitor the slowness of your Angular web app's HTTP requests and API calls


How to find slow HTTP requests that are frustrating users and no doubt causing revenue loss.

Table of content

Introduction

Some web apps act like a dying cow. 😯

And would you believe it?

To make matters worse these web apps are bogged down with those silly loading spinners...

...that seem to think they'll hypnotize us into patiently waiting those extra 8.3 seconds!

It's like waiting on a turtle for a horse ride.

Say, can't we do better?

How can we find the HTTP requests in our Angular application that are too slow? Without needing to install moment.js or any other libraries that will bloat your Angular app?

Once we've uncovered the bottle-necks we can fix them and make your HTTP requests zippy fast.

We could then connect our Angular app to a monitoring service like Application Insights and get alerts for turtle-performance.

Why just imagine it! About the time your boss shows up saying that users are complaining of slowness you'd tell him "I just got done fixing it!" and he'd be so surprised he'd swallow his gum.

Nope, I'm not selling you snake oil. Read on to learn this stuff for yourself, my friend.

Create an Angular HTTP Interceptor

We'll begin by adding one of those cool HTTP Interceptor's to our Angular project.

Open a terminal in your Angular project and whip it up with the Angular CLI like so.

ng generate interceptor monitor

And then we'll import it into our module file by adding it to the providers array.

providers: [
    { 
      provide: HTTP_INTERCEPTORS, 
      useClass: LoadingInterceptor, 
      multi: true
    }
]

And in case you've never heard about Angular HTTP Interceptors, let me explain.

The Angular HTTP Interceptor is a feature in the Angular framework that is used to intercept and modify (if we want) incoming or outgoing HTTP requests. They're commonly used to add authentication tokens to outgoing requests or monitor the status code of a server response and that sort of stuff.

But, in our case, we're going to use this HTTP Interceptor to monitor and alert us of any slow HTTP requests and API issues.

How to use the Angular HTTP Interceptor to monitor API calls

Next we'll open the new monitor.interceptor.ts file. It should look something like this.

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MonitorInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request);
  }
}

And we'll want to modify it to look like this.

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { LoadingService } from '../services/loading.service';

@Injectable()
export class MonitorInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const begin = performance.now();
    return next.handle(request).pipe(
      finalize(() => {
        this.logRequestTime(begin, request.url, request.method);
      })
    );
  }

  private logRequestTime(startTime: number, url: string, method: string) {
    const requestDuration = `${performance.now() - startTime}`;
    console.log(`HTTP ${method} ${url} - ${requestDuration} milliseconds`);
  }
}

So what did we just do?

We created a logRequestTime(startTime: number, url: string, method:string) function that logs the request duration, URL and method of every outgoing HTTP request.

Then, in our intercept function, we grab the current time as our request is being sent, pass it on to the server and wait for a response. Once we've received a response we show how slow our HTTP request was by calling the logRequestTime(...) function.

And that is how to monitor the slowness of any HTTP request in your Angular application.

Conclusion

And that's it! We've built an HTTP interceptor that will monitor every outgoing HTTP request and tell us how long it took.

And now it's up to you buster. You can take that logRequestTime function and jazz it up with whatever kind of functionality you want.

You can customize it to only log requests that take longer than a specified amount of time...

Or send all the logs to a logging service...

Questions or comments? Please don't hesitate to contact me.

Angular Consultant