I have an angular RxJS store, where I try to make an HTTP request within a certain time interval, I have tried both with native RxJS functionality and regular Promises.
Here is my approach for using regular promises
updateLeaderboardHttpRequest(filterBy: CompetitionFilteringOptions) {
// const url = this.endpoint.getUrl();
const _interval = setInterval( () => {
const httpRes = new Promise(resolve => {
const url = this.endpoint.getUrl();
// const response = this.httpClient.get<ServerResponse>(url, this.endpoint.createLeaderboardParams(filterBy)).toPromise();
const response = this.httpClient.get('https://random-data-api.com/api/cannabis/random_cannabis?size=30').toPromise();
console.log('making request')
console.log(response)
resolve(response);
});
httpRes.then(res =>{
console.log(res)
})
}, 10000);
I have made some console.log() statements to ensure, that the requests are fired off correctly.
In the console, I can see that the response that is logged, are logged out correctly, but the main issue is that in the network tab, the request is only fired once or twice, and then just logs the same response over and over again.
I think you have an issue with getting data asynchroniously. Try to subscribe on your httpClient.get and it should work:
this.httpClient.get('https://random-data-api.com/api/cannabis/random_cannabis?size=30').subscribe(res=>{
console.log(res);
})
Edit: I don't know exactly what you want to achieve, but from my understanding I would go the following way for the complete functionality:
ngOnInit(): void {
this.interval = setInterval(() => this.updateLeaderboardHttpRequest(filterOptions), 10000);
}
updateLeaderboardHttpRequest(filterBy: CompetitionFilteringOptions) {
this.httpClient.get('https://random-data-api.com/api/cannabis/random_cannabis?size=30').subscribe(res=>{
console.log(res);
// Update binding to DOM or fire EventEmitter to which any other component can subscribe.
});
}
ngOnDestroy() {
if (this.interval) {
clearInterval(this.interval);
}
}