如何在javascript中获取所有待处理的http请求?

时间:2016-02-11 13:54:06

标签: javascript http request angular

javascript还是angular2

获取待处理的http请求列表?

目标是启动其他几个流程'

根据此清单的波动。

是否存在类似可访问的请求堆栈?

感谢。

2 个答案:

答案 0 :(得分:2)

实际上,您可以扩展Http类来拦截请求执行。

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);
  }

  (...)
}

您可以利用finally运算符来拦截与HTTP请求相对应的可观察对象的完成。您可以在调用之前递增属性,并在finally运算符中递减它。

get(url: string, options?: RequestOptionsArgs): Observable<Response> {
  this.monitoring.pendingRequestsNumber++;
  return super.get(url, options).finally(() => {
    this.monitoring.pendingRequestsNumber--;
  });
}

这个CustomHttp类可以像这样注册。我添加了一个监控服务来存储(和共享)待处理请求的数量:

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]
  })
]);

我创建了一个plunkr,描述了实现这种方法的方法:https://plnkr.co/edit/qHNn5amI0byci9RMkZyE?p=preview

答案 1 :(得分:0)

如果你想这样做,你需要在后端。如果您的网站托管在PHP上,那么您无法在javascript中执行此操作。但是如果你使用node.js,那肯定是可能的,因为node.js在后端使用了javascript。