Search code examples
angularprogress-barangular-http-interceptors

Know the time spent by API request in flight - Angular 9


I am trying to intercept request in angular to know if API is taking more than 5 seconds in flight. If API takes more than 5 seconds then a message needs to be displayed like 'Request in progress, it will take a short while'

I am able to calculate time took by API after getting response as below:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const startTimestamp = +new Date().getTime();
    return next.handle(req).pipe(
      tap(
          (evt: HttpEvent<any>) => {
             const endTimestamp: number = +new Date().getTime();
             // get the difference
             const responseTimes = (endTimestamp - startTimestamp) / 1000;
             console.log(`Request took ${responseTimes} ms`);
          }
      )
}

However, i want to know the time while request is in flight. Any leads will be apprecited.


Solution

  • I think using a setInterval would satisfy your question : (this would check the time spent at the start of the request and current time every 10 ms)

    @Injectable()
    export class MyHttpInterceptor implements HttpInterceptor {
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const t0 = performance.now();
        let interval;
    
        console.log('processing request', request);
        interval = setInterval(() => {
          const t1 = performance.now();
          const responseTime = (t1 - t0) / 1000;
          console.log(`Request took ${responseTime} ms since start`);
        }, 10);
    
        return next.handle(request).pipe(
          tap((ev: HttpEvent<any>) => {
            if (ev instanceof HttpResponse) {
              console.log('processing response', ev);
            }
          }),
          catchError((response) => {
            if (response instanceof HttpErrorResponse) {
              console.log('processing http error', response);
            }
    
            return Observable.throw(response);
          }),
          finalize(() => {
            const t1 = performance.now();
            const totalResponseTime = (t1 - t0) / 1000;
            console.log(`Request finished: took ${totalResponseTime} ms`);
    
            clearInterval(interval);
          }),
        );
      }
    }
    

    demo link