Home > Enterprise >  Angular Timed API calls while running a specific API call
Angular Timed API calls while running a specific API call

Time:10-29

I have a long backend process (30minutes-1hour) that gets called in Angular.

Only while this process is running I would like to send a different request to the backend at timed interval of 10 minutes.

This is an example of the long API call

this.someService
  .apiCall(passedData)
  .subscribe((response:any) => {
      //Other code here
  },
  (error: HttpErrorResponse) => {
      alert(error.message);
  }
);

Here is the call I would like to make every 10 minutes while the above is still in progress

this.otherService.otherApiCall().subscribe((result)=> {}, () => {});

I am unsure if I am supposed to have some special RxJS code that edits the subscribe or there is a different solution.

I already have a HttpInterceptorService that is used as a loading spinner for while processes are running but I don't think I would modify this code for specific API calls to achieve what I am looking for.

CodePudding user response:

I have figure out a way to solve this issue. I added the following to me component.

private alive: boolean = false;
private count = 0;

stayAlive(){
    this.alive = true;
    timer(0, 900000) //runs initially and every 15 minutes 
    .pipe(
      takeWhile(() => this.alive)
    )
    .subscribe(() => {
      this.count = this.count  1;
      console.log('RAN API : '   this.count);
      this.otherService.otherApiCall().subscribe((result)=> {}, () => {});
    });
  }

Then is my long API call would look like this.

methodToCall(){
    this.stayAlive();
    this.someService
      .apiCall(passedData)
      .subscribe((response:any) => {
          //Other code here
      },
      (error: HttpErrorResponse) => {
          alert(error.message);
      },() =>{
          this.alive = false;//will stop running API call every 15 minutes
      }
);
}

I also added this as well

ngOnDestroy(){
  this.alive = false;
}
  • Related