我正在尝试从 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 个浏览量。有办法解决这个问题吗?
最佳答案
您已经在运行您的第一个 HTTP 调用“getList”...您正在使用 forEach 迭代结果并获取 View 计数...一切都很好。
当您调用第二次 HTTP 调用“getViews(id)”时,请确保将结果与 VideoId 的引用一起存储;这样您就可以简单地使用 *ngIf 在结果准备好时显示结果...
HTML
<div *ngFor="let video of videos">
<p> ID# {{video.videoId}}: {{video.title}} "{{video.description}}"</p>
<div *ngFor="let viewership of views">
<span *ngIf="viewership.videoId == video.videoId"> number of views: {{viewership.viewCount}} </span>
</div>
</div>
相关TS:
this.videos.forEach(element =>{
this.views.push({ "videoId":element.videoId, "viewCount": this.getViews(element.videoId) });
});
对于工作演示,请使用 look here - 快乐学习!!
关于angular - 在另一个 API 调用中显示来自 API 调用的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54227806/