繁体   English   中英

Angular 8:如何使用 Observable 的间隔立即发送 http 请求

[英]Angular 8: How to send the http request immediately using interval of Observable

我具有将请求从前端连续发送到后端的功能。 所以我添加了下面给出的代码。

我想以第一个请求应该立即执行 go 的方式实现,然后在两分钟后执行。

但是使用下面的代码并根据间隔的定义,它将在两分钟后发送第一个请求。

this.getData = Observable.interval(2 * 60 * 1000)
      .pipe(flatMap(() => this.service.getData(b, b, b, b, b, b))).subscribe();

我不想通过首先添加请求然后添加上面的代码来重复代码,任何其他方式来完成它。

解决它的最简单的方法是使用timer运算符而不是interval运算符,初始延迟为 0 秒。

this.getData = Observable.timer(0, 2 * 60 * 1000)
      .pipe(flatMap(() => this.service.getData(b, b, b, b, b, b))).subscribe();

更新:使用repeatdelayWhen运算符

上述解决方案对于简单的用例很有用。 但是,如果您需要动态控制每个请求之间的延迟并根据某些条件完成轮询,则可以使用repeatdelayWhentakeWhile运算符。

let condition = 0;
this.service.getData(b, b, b, b, b, b).pipe(
  take(1),
  delayWhen(_ => condition === 0 ? timer(0) : timer(2 * 60 * 1000)),   // set poll delay
  repeat(),
  takeWhile(_ => condition < 5),        // stop polling when `condition` is 5
  switchMap(response => {
    // do something and update the `condition`
    condition++;
    return of(response);
  })
).subscribe(
  res => console.log(res),
  err => console.log(err),
  () => console.log('complete')
);

您还可以使用repeatWhen运算符对何时重复请求进行更精细的控制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM