New to Angular2 here and wondering how to do this async request on array pattern (not so sure about the pattern name).
So let's say I use Angular2's Http to get a YouTube Playlist that contains videoId in each return item. Then I need to loop through this item with the videoId and do another request to YouTube to get the individual video information. This can be another common HTTP request, get the list then loop through the list and get the details of every individual item.
let url = [YouTube API V3 list url]
let detailUrl = 'https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics';
this.http.get(url)
.map(res => res.json())
.subscribe(data => {
let newArray = data.items.map(entry => {
let videoUrl = detailUrl + '&id=' + entry.id.videoId +
'&key=' + this.googleToken;
this.http.get(videoUrl)
.map(videoRes => videoRes.json())
.subscribe(videoData => {
console.log(videoData);
//Here how to I join videoData into each item inside of data.items.
});
});
});
So the above code does work. But I still have these two questions:
How do I join the
videoDataback todata.itemsand make sure the correct item inside thedata.itemsis joined with the correctvideoData(thevideoDatathat is using theentry.id.videoIdof the related item insidedata.items) and create that newnewArray?How do I know when everything is done and do something based on all the data after all the async requests have finished?
The newArray keep the same order of the first HTTP request. As the first HTTP hit the YouTube search list API with order by viewCount. Simply nest observable like above will not keep the original order.
UPDATE
With inoabrian solution, I can successfully achieve the above three points. But when I call the myvideoservice again (like changing the url as new NextPageToken), the Subject - this._videoObject has 2 observers. And load again, it has 3 observers and so on. I need a way to reset the Subject to have only 1 observers so I won't have duplicate videos. Is it a best practice way to clear/reset subject?