user5913732
user5913732

Reputation: 31

How to get all the pending http requests in javascript?

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.

Upvotes: 3

Views: 3387

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202216

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.

Upvotes: 2

Doomer
Doomer

Reputation: 75

You need to be on the backend if you want to do that. If your web site is hosted on php then you cannot do it in javascript. But if you use node.js then it is certainly possible because node.js uses javascript on the backend.

Upvotes: 0

Related Questions