Currently, I am facing a challenge with sending GET requests for a large number of URLs (50 of them) to the Spotify server and then returning their results in a single Observable/array/object.
This is the code snippet I have come up with:
curatedTopArtistTracks(artistIds) {
let responseStore = [];
for (let [index, artistId] of artistIds.entries()) {
let baseURL = `https://api.spotify.com/v1/artists/${artistId}/top-tracks?country=US`;
let response = this.http.get<any>(baseURL, { headers: this.customHeaders });
response.subscribe(
res => {
responseStore.push(res.tracks);
},
error => {
console.log('ERROR IN GETTING RESPONSE : INDEX : ', index);
}
);
}
return responseStore;
}
The URL format is:
https://api.spotify.com/v1/artists/${artistId}/top-tracks?country=US
where ${artistId}
varies dynamically for each of the 50 IDs.
MY OBSERVATIONS
While this function successfully sends the appropriate requests and receives a 200 OK response, the main issue is that the for loop does not wait for the HTTP requests to be resolved and returns an undefined responseStore
.
I looked into concepts like ForkJoin and mergemap in Rxjs
and tried to modify the code as shown below:
Example:
curatedTopArtistTracks(artistIds): Observable<any> {
let responseStore = [];
for (let [index, artistId] of artistIds.entries()) {
let baseURL = `https://api.spotify.com/v1/artists/${artistId}/top-tracks?country=US`;
const requestURL = this.http.get(baseURL);
responseStore.push(requestURL);
}
return forkJoin(responseStore);
}
However, the above code does not initiate fetching responses because it seems that pushing the URLs into an array causes issues with how forkjoin processes them.
If you have any insights on how I can achieve the desired functionality, your help would be greatly appreciated!
UPDATE
As @martin pointed out in the comment below, I was not subscribing to the service. It functions correctly when I do subscribe, as shown below:
let response = this.service.curatedTopArtistTracks(artistArray).subscribe(
res => {
console.log('RESPONSE : ', res);
},
error => {
console.log('error : ', error);
}
)