简体   繁体   中英

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.

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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