angular - rxjs distinct不能与firestore查询一起使用
问题描述
我正在尝试使用 rxjs 在 Angular 中获得不同的 Firestore 值(客户端)distinct()
。我得到和以前一样的结果。
{ id: '2224', city: 'chicago', name: 'jon' },
{ id: '33', city: 'chicago', name: 'bill' },
{ id '223' city: 'chicago', name: 'jon' }
这是我的代码:
query = this.afs.collection('users', ref => ref.where('city' '==', 'chicago'))
.valueChanges({ idField: 'id' })
.pipe(
distinct((a: any) => a.name)
);
我得到所有结果,就好像管道不存在一样。
离开官方文档,我希望得到这个:
{ id: '2224', city: 'chicago', name: 'jon' },
{ id: '33', city: 'chicago', name: 'bill' }
我应该手动使用switchMap或其他东西来过滤结果吗?
解决方案
我相信, usingdistinct()
不是适合您用例的工具。您将得到一个完整的数组作为响应,distinct
将对单个排放起作用。
您可以将阵列转换为单独的排放,您可以在其中看到distict()
所需的工作。
this.afs.collection('users', ref => ref.where('city' '==', 'chicago'))
.valueChanges({ idField: 'id' })
.pipe(
mergeMap((allDocs) => {
return from(allDocs).pipe(distinct((eachDoc) => {
return eachDoc.name;
}))
})
).subscribe((data) => {
console.log(data);
});
在这里你不会得到第二个'Bill',但是,我不认为你想要这种响应,在这里你会得到单个对象而不是数组。这意味着,您的订阅回调将被调用相同的次数,内部 observable 发出。
解决方案: 您可以自己过滤掉数组 reposne,这样的事情对您来说可能是一个很好的解决方案:
this.afs.collection('users', ref => ref.where('city' '==', 'chicago'))
.valueChanges({ idField: 'id' })
.pipe(
map((allDocs) => {
const auxObj = allDocs.reduce((acc, eachDoc) => {
acc[eachDoc.name] = eachDoc;
return acc;
}, {});
return Object.values(auxObj);
})
).subscribe((data) => {
console.log('filtered data', data);
})
推荐阅读
- javascript - 有没有办法检测具有特定类的 div 并将顶部滚动条移动到它在父 div 内的位置?
- sql-server - 如何在sql server中保存变量中的值
- excel - Range.replace 方法不替换任何东西
- ldap - LDAP:在一个查询中从多个 OU 中检索条目
- spring - Spring Feign 客户端调用进入异常块时应该停留在 try 块中
- python - 从文件中填充没有重复数据的列表/列表列表
- rest - CakePHP 3 REST API ajax 登录解决方案
- php - 如果另一个字段与相同的值不同,Laravel 会验证一个字段的某个值
- java - 在java中获取两天之间的可用天数
- terraform - ImportError:无法在 terraform 合规性中导入名称 __VERSION__