Angular2防止在有任何挂起的请求时对http请求进行排队
假设我想每15秒从后端提取一次数据。我的代码现在如下所示:Angular2防止在有任何挂起的请求时对http请求进行排队,angular,Angular,假设我想每15秒从后端提取一次数据。我的代码现在如下所示: Observable.timer(0, 15000).switchMap(() => this.callService()).subscribe(); 测试组件: public ngOnInit(): void { Observable.timer(0, 15000).subscribe(() => { this.callService(); }); } private callServic
Observable.timer(0, 15000).switchMap(() => this.callService()).subscribe();
测试组件:
public ngOnInit(): void {
Observable.timer(0, 15000).subscribe(() => {
this.callService();
});
}
private callService(): void {
this.testService.callBackendService().subscribe(data => {
this.data = data;
});
}
public callBackendSerivce(): Subscribable<Data> {
return this.http.get(this.serviceUrl)
.map(this.extractData)
.catch(this.handleError);
}
public ngOnInit(): void {
this.callService();
}
private callService(): void {
this.testService.callBackendService().subscribe(data => {
this.data = data;
this.subscribeToService();
});
}
private subscribeToService(): void {
this.timerSubscription= Observable.timer(15000).subscribe(() => {
this.callService();
this.timerSubscription.unsubscribe();
});
}
测试服务:
public ngOnInit(): void {
Observable.timer(0, 15000).subscribe(() => {
this.callService();
});
}
private callService(): void {
this.testService.callBackendService().subscribe(data => {
this.data = data;
});
}
public callBackendSerivce(): Subscribable<Data> {
return this.http.get(this.serviceUrl)
.map(this.extractData)
.catch(this.handleError);
}
public ngOnInit(): void {
this.callService();
}
private callService(): void {
this.testService.callBackendService().subscribe(data => {
this.data = data;
this.subscribeToService();
});
}
private subscribeToService(): void {
this.timerSubscription= Observable.timer(15000).subscribe(() => {
this.callService();
this.timerSubscription.unsubscribe();
});
}
两个问题:
根据第二点,您有两种可能性:
Observable.first().subscribe(...)
或
first()take()
允许您设置要订阅的次数(作为参数)。您应该在计时器上使用开关映射
操作符,如下所示:
Observable.timer(0, 15000).switchMap(() => this.callService()).subscribe();
这将每隔15秒调用callService
如果由于任何原因callService
抛出错误,计时器将自动完成,这要归功于开关映射
如果只需要callService
的第一个值,则只需在不使用计时器的情况下调用它即可
HTTP调用总是在成功返回值后完成,因此它们不必取消订阅
如果要在15秒后调用呼叫服务
,则应使用计时器上的延迟时间
可观察。定时器(15000)。开关映射(…)
关于尝试失败后的重试,请查看位于的重试
操作符,我想防止在任何http请求挂起时调用后端服务。在您的示例中,当有任何未决请求时,我将取消此请求并拨打新电话。这不是我要找的。