javascript - 取消 Rx Observable 间隔调用

标签 javascript angularjs typescript angular

我是 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()
        });
}

正如您在订阅方法中看到的那样,我只是想在“trainingStatus”为“COMPLETED”时停止间隔调用(每 2 秒一次)。

最佳答案

这可以通过取消订阅选项实现。

每个 .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()
            }
        });
}

关于javascript - 取消 Rx Observable 间隔调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38334117/

相关文章:

javascript - 使用ReactJS和Material-UI的Fake Select占位符

javascript - 如何绑定(bind)到 AngularJS 中的表单属性?

angularjs - html中的电话号码验证

typescript - 导入本地文件未解决

angular - Angular 中的 html2canvas - 无法调用类型缺少调用签名的表达式

javascript - 无法直接注入(inject) Controller

javascript - 使用 knex js 时如何返回值?

javascript - addEventListener 和数组内部的值递减问题

javascript - 如何异步加载云端点api

html - 带有 X 右上角的 Angular 8 Material 对话框关闭按钮