Currently, I am in the process of retrieving data from the Youtube API by utilizing 2 separate requests. One request is used to fetch a list of videos, while the other request provides details for each individual video.
The initial request successfully displays 4 videos with their corresponding thumbnails and titles. In an attempt to gather more information for each video, I experimented with implementing a foreach loop inside my primary API call:
Below is an excerpt from my service.ts file:
export class YoutubeDataService {
constructor(private http: HttpClient) { }
getList() {
return this.http.get('https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCiRDO4sVx9dsyMm9F7eWMvw&order=date&maxResults=4&type=video&key={MY_KEY}')
}
getViews(id) {
return this.http.get('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=' + id + '&key={MY_KEY}');
}
}
Next, we have my component.ts:
export class VideosComponent implements OnInit {
videos: Object;
items = [];
views: Object;
constructor(private youtube: YoutubeDataService) { }
ngOnInit() {
this.youtube.getList().subscribe(data => {
this.videos = data.items;
console.log(this.videos);
this.videos.forEach(element => {
this.youtube.getViews(element.id.videoId).subscribe(data2 => {
this.views = data2.items[0].statistics.viewCount;
console.log(this.views);
});
});
});
}
}
Lastly, let's take a look at my component.html:
<div class="video col-xl-5" *ngFor="let video of videos.items">
<a class="row" href="https://www.youtube.com/watch?v={{video.id.videoId}}">
<img [src]="video.snippet.thumbnails.medium.url">
<div class="col">
<h3 class="title">{{ video.snippet.title }}</h3>
// Information that requires fetching from second API call
<p class="description">{{ video.snippet.description }}</p>
</div>
</a>
</div>
The code effectively shows the title, thumbnail, and description as intended. Additionally, the console.log(this.views);
accurately displays the view count for each video. However, I am currently facing challenges in managing this data.
UPDATE
Upon further review, it became clear that simply pushing the data into an array would resolve the issue when displaying it within the html using an index: component.ts
this.youtube.getList().subscribe(data => {
this.videos = data.items;
this.videos.forEach(element => {
this.youtube.getViews(element.id.videoId).subscribe(data2 => {
this.array.push(data2.items[0].statistics.viewCount);
});
});
});
However, a new problem arose where the view counts were not ordered according to the videos. Upon each page refresh, the view counts appeared in a different order each time. Is there a possible solution to address this issue?