是否可以在 angular2.xml 中执行“就绪”指示器?我需要以某种方式检测是否有 Angular 工作以避免竞争条件。
这是我需要的,但对于 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
最佳答案
您可以通过扩展 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 。
有关更多详细信息,请参阅此问题:
关于javascript - Angular2 工作指示灯,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36199242/