Angular2 working indicator
是否可以在 angular2.我需要以某种方式检测是否有angular工作以避免竞争条件。
这是我需要的,但对于 angularjs 实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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); } } |
现在实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | @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(); }); } (...) } |
最后一步是在引导应用程序时注册两个类:
1 2 3 4 5 6 7 | 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。
请参阅此问题了解更多详情:
- 如何在javascript中获取所有待处理的http请求?