如何向每个http请求(angular2)添加预加载程序?
在我的angular2应用程序中,我想在每次如何向每个http请求(angular2)添加预加载程序?,angular,angular2-http,Angular,Angular2 Http,在我的angular2应用程序中,我想在每次http请求启动时显示预加载程序(锁定屏幕),并在请求结束后隐藏它。subscribe方法允许我们检测请求何时成功、何时出错或何时完成。我认为每次我在请求中调用subscribe方法时都编写预加载程序的代码是个坏主意 如何检测请求的开始/结束(subscribe方法除外) 向每个请求添加预加载程序的好方法是什么 你可以通过两种方式做到这一点 创建一个DataService和wrapHttp,将其用于调用API,并将预加载程序逻辑置于服务中 您可以使用拦
http
请求启动时显示预加载程序(锁定屏幕),并在请求结束后隐藏它。subscribe方法允许我们检测请求何时成功、何时出错或何时完成。我认为每次我在请求中调用subscribe方法时都编写预加载程序的代码是个坏主意
你可以通过两种方式做到这一点
Http
,将其用于调用API,并将预加载程序逻辑置于服务中拦截器
,这是一个和我更喜欢选项1,它更具可扩展性,您可以从一个地方控制所有调用。我会像下面那样扩展
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);
}
(...)
}
服务实现可以是这样的:
export class NotifierService {
notifier:Subject<any> = new Subject();
notifyBeforeRequest() {
notifier.next();
}
}
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
});
}
}