首页 > 解决方案 > 需要将地图数据(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;
      })
    );
  }

标签: angularrxjsyoutube-apimergemap

解决方案


我想我理解你想要做什么,我们会到达那里,但让我们从头开始。

首先,您可以避免:

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 运算符。它可能看起来更复杂,但结果会更清晰


推荐阅读