Utilizing Spotify's API search feature, I am working with an array of SongSearchParams that consist of title and artist parameters:
export class SongSearchParams {
public title: string;
public artist: string;
constructor(title: string, artist: string){
this.title = title;
this.artist = artist;
}
}
The HTTP request structure is as follows:
searchTrack(searchParams: SongSearchParams, type='track'){
var headers = new Headers({'Authorization': 'Bearer ' + this.hash_params.access_token});
this.user_url = "https://api.spotify.com/v1/search?query="+searchParams.artist+' '+
searchParams.title+"&offset=0&limit=1&type="+type+"&market=US";
return this.http.get(this.user_url, {headers : headers})
.map(res => res.json());
}
Within a TypeScript file of one of my components, I have access to the SongSearchParams array. When a specific button is clicked, I aim to pass each element of this array through the searchTrack function to fetch details like album image, track name, and artist of a song.
onClick(){
for(let searchQuery of this.songService.songSearches){
this.spotifyserv.searchTrack(searchQuery)
.subscribe(res => {
this.searchedSong.artist = res.tracks.items[0].artists[0].name;
this.searchedSong.title = res.tracks.items[0].name;
this.searchedSong.imagePath = res.tracks.items[0].album.images[0].url;
console.log(this.searchedSong);
this.songService.addSong(this.searchedSong);
})
}
}
Upon execution of this code, it seems only the last song in the array is persistently stored despite logging all songs correctly during iterations.
To resolve this issue, some resources suggest utilizing Promises sequentially via the then() method. Therefore, I attempted to incorporate this into the searchTrack functionality:
A potential problem could lie within my addSong function implementation:
addSong(song: Song){
this.songs.push(song);
this.songsChanged.next(this.songs.slice());
}
If the above function appears correct, considering another approach like chaining promises might be beneficial (despite failed attempts).