Angular 4中的长轮询 [英] Long Polling in Angular 4

查看:440
本文介绍了Angular 4中的长轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要进行API调用以显示进度.

I need to do API calls to display the progress of something.

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

I have created a service which does this every 1.5 seconds

主要组件

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));
}

该呼叫有效,但仍在继续.进度完成(if (!data.InProgress)后,我想停止进行API调用,但是我对此感到困惑.

The call works, but it keeps going. I want to stop doing the API call when the progress is finished (if (!data.InProgress) but I'm stuck on this.

if (!data.InProgress)时如何正确取消订阅此可观察的东西?

How can I correctly unsubscribe from this observable when if (!data.InProgress)?

谢谢

推荐答案

您可以使用takeWhile运算符.

以下是文档: http://reactivex.io/rxjs/class /es6/Observable.js~Observable.html#instance-method-take同时

发出源可观察到的值,只要每个值 满足给定谓词,然后在完成后立即完成 谓词不满足.

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

Here is a generic example: 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));
}

这篇关于Angular 4中的长轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆