angular - 需要将地图数据(youtube api 播放列表)与其他数据(播放列表的视频编号)合并
问题描述
我已成功显示我的播放列表,但我想将视频数量添加到每个播放列表。
为此,我必须发送另一个请求。我无法合并播放列表结果中的视频数量
感谢您的帮助,3天没有结果
我的 yt.service.ts
getPlaylistsForChannel(channel): Observable<any[]> {
return this.http
.get<any[]>(
"https://www.googleapis.com/youtube/v3/playlists?key=" +
this.apiKey +
"&channelId=" +
channel +
"&part=snippet,id&maxResults=20"
)
.pipe(
catchError(err => of([])),
map(res => {
return res["items"];
})
);
}
getListVideos(listId): Observable<any[]> {
console.log(listId);
return this.http
.get<any[]>(
"https://www.googleapis.com/youtube/v3/playlistItems?key=" +
this.apiKey +
"&playlistId=" +
listId +
"&part=snippet,id&maxResults=20"
)
.pipe(
catchError(err => of([])),
map(res => {
console.log(res["items"]);
return res["items"];
})
);
}
我的播放列表.ts
searchPlaylists() {
this.playlists = this.ytService.getPlaylistsForChannel(this.channelId);
let that = this;
this.playlists = this.playlists.pipe(
catchError(err => of([])),
mergeMap(res => {
let nb = res.length;
for (let i = 0; i < nb; i++) {
that.ytService.getListVideos(res[i].id).pipe(
map(res2 => {
res.number = res2.length;
})
);
}
console.log(res);
return res;
})
);
}
解决方案
我想我理解你想要做什么,我们会到达那里,但让我们从头开始。
首先,您可以避免:
let that = this;
通过使用箭头函数:
searchPlaylists = () => {
还可以尝试使用有意义的变量名,这对于以前从未见过您的代码的人来说更容易理解发生了什么。让我们写得更清楚一点:
lists: any[];
searchPlaylists = () =>
this.ytService
.getPlaylistsForChannel(this.channelId)
.pipe(
catchError((err) => of([])),
mergeMap((playlists) =>
playlists.map(async (playlist) => {
const videoList = await this.ytService
.getListVideos(playlist.id)
.toPromise();
return { ...playlist, number: videoList.length };
})
)
)
.subscribe((updatedLists) => (lists = updatedLists));
要记住的事情:
- 你必须订阅才能看到值的变化,然后你必须分配这些值
- 当您检查正在异步运行的事物以及何时期望分配这些事物时,您必须小心
- 你需要熟悉 ES6 语法和 RXJS 操作符
- 客户端不应该处理这种逻辑。这无法扩展。如果播放列表的数量变得巨大,HTTP 调用的数量就会太多
还要注意@kai 的回答,他建议使用不同的 RXJS 运算符。它可能看起来更复杂,但结果会更清晰
推荐阅读
- c - 嵌入式 GCC 优化魔法
- java - Eclipse 中用户“@'localhost'(使用密码:NO)的访问被拒绝,而不是 'root'@'localhost',类路径已损坏
- r - 当使用 flexdashboard 生成的 html 文件在本地打开时,有没有办法让图形渲染?
- javascript - React JS:渲染的钩子比预期的要少。这可能是由于意外提前退货声明造成的
- css - 基于类的 Stencil 组件上的样式宿主元素
- android - 在 Android 10 上的 Xamarin 表单中使用权限请求遇到可解释的问题
- json - 无法将文本数据转换为 json
- html -
- angular - IIS:在同一站点下托管 2 个 SPA
- docker - Docker 在 Kubernetes 中的 docker 路由