How can I get the total number of pending requests in Angular5 like $http.pendingRequests
in AngularJS?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With