我正在try 使用以下函数转换来自YouTube搜索API的GET请求.

第一个映射应该为我获取响应对象中的项. 使用第二个映射,我希望将这些项映射到我的Custom Class SearchResult. 但由于某些原因,第二个映射中总是有完整的项目列表,而不是迭代单个元素.因此,管道不会返回带有SearchResult元素数组的可观测对象.

13号角 RxJS 7.5

  search(query: string) : Observable<SearchResult[]>{
    const params: string = [
      `q=${query}`,
      `key=${this.apiKey}`,
      `part=snippet`,
      `type=video`,
      `maxResults=10`
    ].join('&');
    const queryUrl = `${this.apiUrl}?${params}`;
    return this.http.get(queryUrl).pipe(
      map((response : any) => response.items),
      map(item => {
        return new SearchResult({
          id: item.id.videoId,
          title: item.snippet.title,
          description: item.snippet.description,
          thumbnailUrl: item.snippet.thumbnails.high.url
        });
      }),
    )}
  }

推荐答案

第一个map从响应返回items数组,第二个map应该使用Array.map()函数将数组项映射到所需的模型.

RxJS的map操作符并不遍历数组项,而是将流中发出的每个值映射到其他值.

您可以按如下方式进行处理:

search(query: string): Observable<SearchResult[]> {
  const params: string = [
    `q=${query}`,
    `key=${this.apiKey}`,
    `part=snippet`,
    `type=video`,
    `maxResults=10`,
  ].join('&');
  const queryUrl = `${this.apiUrl}?${params}`;
  return this.http.get(queryUrl).pipe(
    map((response: any) => response.items),
    map((items) =>
      items.map(
        (item) =>
          new SearchResult({
            id: item.id.videoId,
            title: item.snippet.title,
            description: item.snippet.description,
            thumbnailUrl: item.snippet.thumbnails.high.url,
          })
      )
    )
  );
}

你可以在这里阅读更多信息:https://rxjs.dev/api/operators/map

Javascript相关问答推荐

单击按钮后未清除 Select

如何从对象嵌套数组的第二级对象中过滤出键

将数据从strapi提取到next.js,但响应延迟API URL

根据总价格对航班优惠数组进行排序并检索前五个结果- Angular HTTP请求

在贝塞尔曲线的直线上找不到交叉点:(使用@Pomax的bezier.js)

TypScript界面中的Infer React子props

过滤对象数组并动态将属性放入新数组

PrivateRoute不是路由组件错误

显示图—如何在图例项上添加删除线效果?

如何从网站www.example.com获取表与Cheerio谷歌应用程序脚本

Use Location位置成员在HashRouter内为空

MarkLogic-earch.suggest不返回任何值

如何在FastAPI中为通过file:/URL加载的本地HTML文件启用CORS?

无法设置RazorPay订阅API项目价格

Node.js API-queryAll()中的MarkLogic数据移动

select 2-删除js插入的项目将其保留为选项

在没有任何悬停或其他触发的情况下连续交换图像

TypeORM QueryBuilder限制联接到一条记录

使用props 将VUE 3组件导入JS文件

AstroJS混合模式服务器终结点返回404