简体   繁体   English

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

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

I have the functionality to send the request from frontend to backend continuosly.我具有将请求从前端连续发送到后端的功能。 so I added the code as given below.所以我添加了下面给出的代码。

I want to implement in way that the first request should go immediately and then after two minutes.我想以第一个请求应该立即执行 go 的方式实现,然后在两分钟后执行。

but with below code and as per definition of interval, it will send the first request after two min.但是使用下面的代码并根据间隔的定义,它将在两分钟后发送第一个请求。

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

I dont want to repeat the code by adding a request first and then adding the above code, any other way to accomplish it.我不想通过首先添加请求然后添加上面的代码来重复代码,任何其他方式来完成它。

The most trivial way to solve it would be to usetimer operator instead of interval operator with an initial delay of 0 seconds.解决它的最简单的方法是使用timer运算符而不是interval运算符,初始延迟为 0 秒。

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

Update: using repeat and delayWhen operators更新:使用repeatdelayWhen运算符

The above solution would be useful for simple use-cases.上述解决方案对于简单的用例很有用。 If you however need to dynamically control the delay between each request and complete the polling based on some condition, you could use repeat , delayWhen and takeWhile operators.但是,如果您需要动态控制每个请求之间的延迟并根据某些条件完成轮询,则可以使用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')
);

You could also userepeatWhen operator to have more refined control on when the request will be repeated.您还可以使用repeatWhen运算符对何时重复请求进行更精细的控制。

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

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