Is there a way in javascript or angular2
to get the list of pending http requests?
The goal is to start 'several other processes'
according to the fluctuation of this list.
Does something like an accessible stack of requests exist?
Thanks.
In fact you can extend the Http class to intercept request execution.
import {Injectable} from 'angular2/core';
import {Http,ConnectionBackend,RequestOptions,RequestOptionsArgs,Request} from 'angular2/http';
import 'rxjs/Rx';
import {MonitoringService} from './monitoring.service';
@Injectable()
export class CustomHttp extends Http {
constructor(backend: ConnectionBackend,
defaultOptions: RequestOptions,
private monitoring:MonitoringService) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
console.log('request...');
return super.request(url, options);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
console.log('get...');
return super.get(url, options);
}
(...)
}
You can leverage the finally operator to intercept the completion of observables corresponding to HTTP requests. You can increment a property before the call and decrement it in the finally operator.
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
this.monitoring.pendingRequestsNumber++;
return super.get(url, options).finally(() => {
this.monitoring.pendingRequestsNumber--;
});
}
This CustomHttp class can be registered like this. I added a monitoring service to store (and share) the number of pending requests:
import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {HTTP_PROVIDERS,Http,XHRBackend,RequestOptions} from 'angular2/http';
import {AppComponent} from './app.component';
import {CustomHttp} from './http.custom';
import {MonitoringService} from './monitoring.service';
bootstrap(AppComponent, [HTTP_PROVIDERS,
MonitoringService,
provide(Http, {
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, monitory:MonitoringService) => new CustomHttp(backend, defaultOptions, monitory),
deps: [XHRBackend, RequestOptions, MonitoringService]
})
]);
I created a plunkr describing the way to implement this approach: https://plnkr.co/edit/qHNn5amI0byci9RMkZyE?p=preview.
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