While waiting for the completion of one API call, I am recursively consuming an external API. The http calls are being made using
import {HttpClient} from '@angular/common/http'
As a newcomer to the framework, there may be something wrong in the code but the workflow is as follows:
The initial API call is made by this block of code:
initializeCrawling(): void {
this.callCrawlInitializingAPI() // this method is calling the api
.subscribe(
restItems => {
this.groupCrawlingRestResponse = restItems;
console.log(this.groupCrawlingRestResponse);
this.isCrawlActive = false;
}
)
this.fetchResults(); // while callCrawlInitializingAPi call executes, this block here must executed on paralel.
}
I am now declaring a global
boolean
variable that will become false
when this.callCrawlInitializingAPI()
finishes executing.
Here is the code for the second API call which needs to be called recursively:
fetchResults(): void {
this.fetchDataApiCall()
.subscribe(
restItems => {
this.groupCrawlingRestResponse = restItems;
console.log(this.groupCrawlingRestResponse);
}
)
}
fetchDataApiCall() {
do {
this.http
.get<any[]>(this.fetchResultsUrl, this.groupCrawlingResultRestResponse)
.pipe(map(data => data));
console.log("Delaying 3000");
} while (this.isCrawlActive);
}
The goal here is to introduce a delay in the do-while loop, perhaps by 1 second.
I have tried the following methods: 1 - Imported {delay} from "rxjs/internal/operators" and used it as shown above;
do {
this.http
.get<any[]>(this.fetchResultsUrl, this.groupCrawlingResultRestResponse)
.pipe(map(data => data));
console.log("Delaying 3000");
delay(3000);
} while (this.isCrawlActive);
2- Used the setTimeout() function as follows:
do {
setTimeout(function(){
this.http
.get<any[]>(this.fetchResultsUrl, this.groupCrawlingResultRestResponse)
.pipe(map(data => data));}, 1000)
} while (this.isCrawlActive)
None of these approaches seem to be working, and the do-while loop does not appear to be delayed, leading to multiple calls being processed continuously within the loop.
Primarily, I would like to know how to make it work, and secondly, if there's a better way of achieving this with Angular considering my beginner status with the framework.
Thank you
UPDATE
If anyone searches for this issue in the future, my question has a correct answer.
The only modification I had to make was in this line of code
clearInterval(intervalHolder.id)