【问题标题】:Long Polling in Angular 4Angular 4中的长轮询
【发布时间】:2018-03-25 12:45:10
【问题描述】:

我需要调用 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?

谢谢

【问题讨论】:

    标签: angular typescript long-polling


    【解决方案1】:

    我已经解决了这个问题,方法是将服务调用放入一个变量中,并在完成后取消订阅该变量。

    结果如下:

    public getExportProgress(type: string, requestId: string): any {
        let progress = Observable.interval(1500)
            .switchMap(() => this.http.get(this.apiEndpoint + "Definition/" + type + "/Progress/" + requestId))
            .map((data) => data.json().Data)
            .subscribe(
            (data) => {              
                if (!data.InProgress) {
                    this.toastyCommunicationService.addSuccesResponseToast("done");
                    progress.unsubscribe();
                }            
            },
            error => this.handleError(error));
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用takeWhile 运算符。

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

      发射源 Observable 发出的值,只要每个值 满足给定的谓词,然后完成 谓词不满足。

      这是一个通用示例: 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));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-22
        • 2013-08-08
        • 2011-04-20
        • 2019-05-28
        • 2011-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多