Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total Nos of pending http requests in angular 5

How can I get the total number of pending requests in Angular5 like $http.pendingRequests in AngularJS?

like image 279
Yash Majithiya Avatar asked Mar 05 '18 11:03

Yash Majithiya


1 Answers

Note that code below is written for Angular 8. There might be some little syntax changes since angular 5 but the general idea stays the same

First of all create a http interceptor. You might want to create another service with BehaviorSubject holding request count to be able to inject that service anywhere and subscribe to counter value. If you have an application state (i.e. when you use ngrx) just keep the counter value in store. Injecting interceptor anywhere would be a very bad practice.

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

export class RequestCountHttpInterceptor implements HttpInterceptor {
  pendingRequestsCount = 0;

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler,
  ): Observable<HttpEvent<any>> {
    this.pendingRequestsCount++;
    return next
      .handle(request)
      .pipe(finalize(() => this.pendingRequestsCount--));
  }
}

Next you have to put it in your providers in AppModule (to make sure there is only one instance of this interceptor across whole app)

import { HTTP_INTERCEPTORS } from '@angular/common/http';
...

@NgModule({
 ...
  providers: [
    ...
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestCountHttpInterceptor,
      multi: true,
    },
  ],
  ...
})
export class AppModule {}

And that's it. Request count will be in the instance of HttpRequestCountInterceptor now (as mentioned above move it to another service or th the store).

like image 131
Mat-Dob-Dev Avatar answered Oct 17 '22 07:10

Mat-Dob-Dev