假设我想每15秒从后端提取数据.我的代码现在看起来像这样:
TestComponent:
public ngOnInit(): void { Observable.timer(0,15000).subscribe(() => { this.callService(); }); } private callService(): void { this.testService.callBackendService().subscribe(data => { this.data = data; }); }
TestService的:
public callBackendSerivce(): Subscribable<Data> { return this.http.get(this.serviceUrl) .map(this.extractData) .catch(this.handleError); }
问题是,当后端出现一些错误并且处理时间超过15秒时,此代码将再次点击后端服务,并且再次等待响应.我想防止这种行为,只有在我收到上一次通话的回复时才打电话给服务.怎么实现这个?
我认为它应该是这样的:
TestComponent:
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.timer是否有方法获得第一个结果并自动取消订阅?它会阻止添加此代码:
this.timerSubscription.unsubscribe();