加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 4中的长轮询

发布时间:2020-12-17 06:48:13 所属栏目:安全 来源:网络整理
导读:我需要做API调用来显示某些内容的进度. 我创建了一个服务,每1.5秒执行一次 主要部分 private getProgress() { this.progressService.getExportProgress(this.type,this.details.RequestID); } Services.ts public getExportProgress(type: string,requestId:
我需要做API调用来显示某些内容的进度.

我创建了一个服务,每1.5秒执行一次

主要部分

private getProgress() {
        this.progressService.getExportProgress(this.type,this.details.RequestID);
    }

Services.ts

public getExportProgress(type: string,requestId: string) {
    Observable.interval(1500)
        .switchMap(() => this.http.get(this.apiEndpoint + "Definition/" + type + "/Progress/" + requestId))
        .map((data) => data.json().Data)
        .subscribe(
        (data) => {
            if (!data.InProgress)
                //Stop doing this api call
        },error => this.handleError(error));
}

这个电话有效,但它一直在继续.我想在进度结束时停止进行API调用(if(!data.InProgress)但是我坚持这一点.

如果if(!data.InProgress),我怎样才能正确取消订阅此observable?

谢谢

解决方法

您可以使用takeWhile运算符.

这是文档:
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-takeWhile

Emits values emitted by the source Observable so long as each value
satisfies the given predicate,and then completes as soon as this
predicate is not satisfied.

这是一个通用的例子:
https://rxviz.com/v/yOE6Z5JA

Rx.Observable
  .interval(100)
  .takeWhile(x => x < 10)
  .subscribe(x => { console.log(x); });

以下是您的代码示例:

public getExportProgress(type: string,requestId: string) {
    Observable.interval(1500)
        .switchMap(() => this.http.get(this.apiEndpoint + "Definition/" + type + "/Progress/" + requestId))
        .map((data) => data.json().Data)
        .takeWhile((data) => data.InProgress)
        .subscribe(
        (data) => {
            ...
        },error => this.handleError(error));
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读