【发布时间】:2019-01-17 01:36:45
【问题描述】:
我正在尝试从 Youtube API 获取数据。我正在使用 2 个请求,一个用于视频列表,一个用于每个视频的详细信息。
我的第一个请求有效,我显示了 4 个带有缩略图、标题等的视频... 为了获取每个视频的更多信息,我在我的第一个 API 调用中尝试了一个 foreach 循环:
这是我的service.ts
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}');
}
}
这是我的 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);
});
});
});
}
}
还有我的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="titre">{{ video.snippet.title }}</h3>
// Here I'd like to display infos I can only get from the second API call
<p class="description">{{ video.snippet.description }}</p>
</div>
</a>
</div>
这里,代码按预期显示了标题、缩略图和描述,我的console.log(this.views);显示了每个视频的观看次数,但我找不到如何管理它。
更新
我知道我只需要将数据推送到数组中并在我的 html 中使用索引显示它: 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);
});
});
});
但我遇到了一个新问题:观看次数不是按视频排序的。每次我刷新页面时,它都会以不同的顺序显示 4 个观看次数。有没有办法解决这个问题?
【问题讨论】:
标签: angular typescript