首页 > 解决方案 > 多次点击 URL 最多 1 分钟

问题描述

我有一个角度函数,它返回状态为“继续”或“完成”的数据集。我想继续拨打电话,直到状态返回“完成”,但最多只能持续一分钟。我怎样才能在角度实现这一点

public getLeadsResponse(key: any) {
    this._service.getLeadsData(key).subscribe((response: any) => {
        if (response) {
            if (response.payload.status == "running") {
    // here if i repeate this function it will start an infinite loop if status is always "running"
                this.getLeadsResponse(key);
            }
            else if (response.payload.status == "finished") {
                this.items = res.payload.result;
            }
        }
    })
}

标签: angularrxjs

解决方案


您可以使用expand()

import { of, EMPTY, timer } from 'rxjs'; 
import { expand, map, filter, takeUntil } from 'rxjs/operators';

const makeHttpRequest$ = timer(1000).pipe(map(() => Math.random() > 0.9 ? 'finished' : 'continue'));

const source = of(null).pipe(
  expand(value => value === 'finished' ? EMPTY : makeHttpRequest$),
  filter(value => value !== null), // Ignore the first `of(null)` that triggered the chain.
  takeUntil(timer(60 * 1000)),
);

source.subscribe(console.log);

现场演示:https ://stackblitz.com/edit/rxjs-8n11jj?devtoolsheight=60


推荐阅读