首页 > 解决方案 > RxJS distinct 运算符没有从对象数组中获取不同的值

问题描述

我正在使用图像 API 来提取一些图像信息,并且我想为返回的每个图像创建一个具有唯一作者姓名的数组。我正在使用distinctRxJS 尝试执行此操作,但现在正在返回整个对象。

以下是 API 数据返回的样子:

[
  {
    "id": "117",
    "author": "Daniel Ebersole",
    "width": 1544,
    "height": 1024,
    "url": "https://unsplash.com/photos/Q14J2k8VE3U",
    "download_url": "https://picsum.photos/id/117/1544/1024"
  },
  {
    "id": "118",
    "author": "Rick Waalders",
    "width": 1500,
    "height": 1000,
    "url": "https://unsplash.com/photos/d-Cr8MEW5Uc",
    "download_url": "https://picsum.photos/id/118/1500/1000"
  }
]

以下是我为便于阅读而简化的部分代码:

export class AppComponent {

  authors; // using an array of strings for this doesn't work when I try to set it from the subscribe()

  ngOnInit() {
    const apiURI = 'https://picsum.photos/v2/list?page=2&limit=100';

    const authors$ = this.http.get(apiURI).pipe(
      distinct((item: Image) => item.author),
      tap(author => console.log(author))
    );

    authors$.subscribe(authors => this.authors = authors);
  }

  constructor(private http: HttpClient) { }
}

export interface Image {
    id: number;
    author: string;
    width: number;
    height: number;
    url: string;
    download_url: string;
}

StackBlitz

这对我来说很奇怪,因为我发现了另一个StackBlitz示例,这些示例对一组对象执行基本相同的操作。

这是我第一次与distinct操作员合作,所以我确定我遗漏了一些东西,但我无法弄清楚它是什么。谢谢。

标签: angularrxjs

解决方案


this.http.get 将发出值数组 - 而不是单独的每个值。这就是为什么 distinct 在这里无效。但是您可以使用 mergeAll 运算符转换值数组以分别发出每个值

const authors$ = this.http.get(apiURI).pipe( mergeAll(), distinct((item: Image) => item.author) );


推荐阅读