我是Angular 2的新手,所以这可能是微不足道的 - 我试图弄清楚如何取消每2秒发生一次的Rx.Observable间隔调用。我用这个订阅了Rx.Observable:
getTrainingStatusUpdates() {
this.trainingService.getLatestTrainingStatus('train/status')
.subscribe(res => {
this.trainingStatus = res;
if (this.trainingStatus == "COMPLETED") {
//Training is complete
//Stop getting updates
}
});
}
这是我的service.ts文件中处理我的Rx.Observable间隔调用的方式(这是由上面的函数从另一个文件中调用的):
getLatestTrainingStatus(url: string) {
return Rx.Observable
.interval(2000)
.flatMap(() => this._http.get(url))
.map(<Response>(response) => {
return response.text()
});
}
正如您在订阅方法中所看到的,我只想在“训练状态”时停止间隔呼叫(每2秒钟)。已完成&#39;。
答案 0 :(得分:4)
使用取消订阅选项即可。
每个.subscribe()都返回一个订阅对象。此对象允许您取消订阅基础Observable。
getTrainingStatusUpdates() {
// here we are assigning the subsribe to a local variable
let subscription = this.trainingService.getLatestTrainingStatus('train/status')
.subscribe(res => {
this.trainingStatus = res;
if (this.trainingStatus == "COMPLETED") {
//this will cancel the subscription to the observable
subscription.unsubscribe()
}
});
}
&#13;
答案 1 :(得分:1)
getTrainingStatusUpdates() {
this.trainingService.getLatestTrainingStatus('train/status')
.do(res => this.trainingStatus = res)
.first(res => res == "COMPLETED")
.subscribe(/* Do stuff, if any */);
}
您无需取消订阅/停止间隔。它将在res == "COMPLETED"