【问题标题】:How to unsubcribe a timer service call using takeUntil如何使用 takeUntil 取消订阅计时器服务调用
【发布时间】:2019-08-22 10:07:34
【问题描述】:

我在一定的时间间隔后定期调用服务。我在服务响应中得到两个数字,我想比较这些数字,如果它们相等,我想结束服务调用。那我应该如何使用 takeUntil() 方法呢?

我尝试在 takeUntil() 中使用 this.ngXUnsubscribe,它不会在一段时间内结束服务调用。 ngXUnsubscribe 定义如下:

protected ngXUnsubscribe: Subject<void> = new Subject<void>();
 const source = timer(1000,60000);
        source.subscribe(()=> {
        this._helper.runStatus(id)
        .pipe(first(),takeUntil())
        .subscribe(response => {

            let xyz = response && response.runScenariosDTO ? response.runScenariosDTO : []; 
            this.passDataToParent(xyz);
            this.progressBarData = this.ScenariosBasedOnTypeDTO.map(scenario => {

                let pBar = response && response.runScenariosDTO ? response.runScenariosDTO.find(barData => barData.scenarioId ? barData.scenarioId === scenario.scenarioId : undefined) : undefined;
                this.showStatusAfterLoad = 1;

                return this.prepareProgressBarData(scenario, pBar);
             });

            });
         });

我想在这两个数字相等时停止执行,直到那时我应该继续调用服务。

我得到的 JSON 数据是

{
  "runId": 0,
  "runScenariosDTO": [
    {
      "scenarioId": 0,
      "totalDataset": 0,
      "totalExecuted": 0,
      "totalFailed": 0,
      "totalPassed": 0
    }
  ],
  "totalScenarios": 0
}

所以,在runScenariosDTO的数组中,我想将所有totalExecuted和totalDataset相加,然后我想比较它们。

【问题讨论】:

    标签: angular timer angular6 angular2-services unsubscribe


    【解决方案1】:

    您应该利用 takeWhile 运算符 (examples)。

    timer(1000, 60000).pipe(
      switchMap(() => this._helper.runStatus(id)),
      takeWhile(response => {
        const totals = response.runScenariosDTO.map(v => ({ 
           dataset: v.totalDataset, 
           executed: v.totalExecuted 
        }))
        .reduce((sums, v) => ({ 
           dataset: sums.dataset + v.dataset,
           executed: sums.executed + v.executed 
        }), { dataset: 0, executed: 0 });
    
        return totals.dataset !== totals.executed;
      })
    ).subscribe(...);
    

    【讨论】:

    • 对不起,我忘了说,在我的回复中,我得到了一个 JSON 2d 数组。所以我想找到所有这些变量的总和,然后比较它们......如何比较它们?
    • @AdityaPandya 发布一个 JSON 示例。来自哪个服务电话? runStatus?
    • 我已经更新了这个问题。请看一下。@LppEdd
    • runScenariosDTO 是一个数组,所以我无法直接访问它的属性。我想对所有的 totalExecuted 和 totalDataset 求和,然后比较它们
    • 我在 response.runScenariosDTO、sums.dataset 和 v.dataset 看到一个错误,表明 Object 可能未定义。该怎么办?
    猜你喜欢
    • 2017-04-10
    • 2023-03-24
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 2021-09-03
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多