Angular2工作指标

时间:2016-03-24 11:36:33

标签: javascript angular

是否可以做好准备" angular2指标。我需要以某种方式检测角度是否工作以避免竞争条件。

这是我需要的,但对于angularjs实现:

var el = document.querySelector('[ng-app], [data-ng-app]');
window.angularReady = false;
if (angular.getTestability) {
    angular.getTestability(el).whenStable(function() {  
        window.angularReady = true; 
    });
} else {
    var $browser = angular.element(el).injector().get('$browser');           
    if ($browser.outstandingRequestCount > 0) { 
        window.angularReady = false; 
    }
    $browser.notifyWhenNoOutstandingRequests(function() {
        window.angularReady = true; 
    });
}

https://github.com/wrozka/capybara-angular/blob/master/lib/capybara/angular/waiter.rb#L51-L61

1 个答案:

答案 0 :(得分:3)

您可以通过扩展Http类来实现此功能。

首先创建一个监控服务,您可以在此类中使用该服务来监控正在进行的请求:

export class MonitoringService {
  private outstandingRequestsNumber: int = 0;
  private outstandingRequestsNumberObserver: Observer;
  private outstandingRequestsNumberObservable: Observable;

  constructor() {
    this.outstandingRequestsNumberObservable = Observable.create((observer:Observer) => {
      this.outstandingRequestsNumberObserver = observer;
    }).share();
  }

  getOutstandingRequests() {
    return this.outstandingRequestsNumber;
  }

  incrementOutstandingRequests() {
    this.outstandingRequestsNumber++;
  }

  decrementOutstandingRequests() {
    this.outstandingRequestsNumber--;
    if (this.outstandingRequestsNumber === 0) {
      this.outstandingRequestsNumberObserver.next();
    }
  }

  notifyWhenNoOutstandingRequests(callback) {
    this.outstandingRequestsNumberObservable.subscribe(callback);
  }
}

现在执行CustomHttp类:

    @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...');
    this.monitoring.incrementOutstandingRequests();
    return super.request(url, options).finally(() => {
      console.log('finally');
      this.monitoring.decrementOutstandingRequests();
    });
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    this.monitoring.incrementOutstandingRequests();
    return super.get(url, options).finally(() => {
      console.log('finally');
      this.monitoring.decrementOutstandingRequests();
    });
  }

  (...)
}

最后一步包括在引导应用程序时注册两个类:

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/lXn5vKY1K2A8RvSsJWm3?p=preview

有关详细信息,请参阅此问题: