在我的 angular2 应用程序中,我想在每次http
请求开始时显示一个预加载器(锁定屏幕)并在请求结束后隐藏它。subscribe 方法允许我们检测请求何时成功、出现错误或完成。我认为每次在请求上调用 subscribe 方法时编写预加载器的代码是个坏主意。
- 如何检测请求开始/结束(订阅方法除外)?
- 将预加载器添加到每个请求的好方法是什么?
在我的 angular2 应用程序中,我想在每次http
请求开始时显示一个预加载器(锁定屏幕)并在请求结束后隐藏它。subscribe 方法允许我们检测请求何时成功、出现错误或完成。我认为每次在请求上调用 subscribe 方法时编写预加载器的代码是个坏主意。
我会Http
像下面这样扩展类并添加一个包含可观察/主题的服务,以便在执行 HTTP 请求时得到通知
export class CustomHttp extends Http {
constructor(backend: ConnectionBackend,
defaultOptions: RequestOptions,
private _notifierService:NotifierService) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
this._notifierService.notifyBeforeRequest();
return super.request(url, options);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
this._notifierService.notifyBeforeRequest();
return super.get(url, options);
}
(...)
}
如下所述注册它:
bootstrap(AppComponent, [HTTP_PROVIDERS,
{
provide: Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, notifyService:NotifierService) => {
return new CustomHttp(backend, defaultOptions, notifyService);
},
deps: [XHRBackend, RequestOptions, NotifierService]
}
]);
服务实现可能是这样的:
export class NotifierService {
notifier:Subject<any> = new Subject();
notifyBeforeRequest() {
notifier.next();
}
}
您可以通过以下方式收到通知:
@Component({
(...)
})
export class SomeComponent {
constructor(private notifyService:NotifierService) {
this.notifyService.notifier.subscribe(() => {
// do something
});
}
}