angular - RxJS distinct 运算符没有从对象数组中获取不同的值
问题描述
我正在使用图像 API 来提取一些图像信息,并且我想为返回的每个图像创建一个具有唯一作者姓名的数组。我正在使用distinct
RxJS 尝试执行此操作,但现在正在返回整个对象。
以下是 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示例,这些示例对一组对象执行基本相同的操作。
这是我第一次与distinct
操作员合作,所以我确定我遗漏了一些东西,但我无法弄清楚它是什么。谢谢。
解决方案
this.http.get 将发出值数组 - 而不是单独的每个值。这就是为什么 distinct 在这里无效。但是您可以使用 mergeAll 运算符转换值数组以分别发出每个值
const authors$ = this.http.get(apiURI).pipe( mergeAll(), distinct((item: Image) => item.author) );
推荐阅读
- node.js - 如何在环回中手动连接到 MongoDB 数据库?
- sql - 透视/转置标题表到行
- python - 如何从 Flask 在 SQLAlchemy 中重新创建数据库?
- php - '调用数组上的成员函数 paginate()' 多个连接表发生错误
- python - 如何将数据集读取为列表的字典
- python - 使用 reduce 计算节点的 gini 指数
- c# - Telerik RadAsynUpload VM293:3 Uncaught SyntaxError: Unexpected token < in JSON at position 2
- web-scraping - 允许处理/迭代/查询科学文章的免费 API/库(即 Google Scholar)?
- javascript - 如何让 Flex 在我的 react 应用程序中工作?
- python - 我应该如何创建为使用 scipy.optimize.least-squares 拟合阻抗数据提供残差的函数?