rxjs distinct 不适用于 firestore 查询

rxjs distinct not working with firestore query

我正在尝试在 angular 和 distinct() 中使用 rxjs 获取不同的 firestore 值(客户端)。我得到了和以前一样的结果。

{ 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)
);

我得到的所有结果就好像 管道 不存在一样。

离开 official doc,我希望得到这个:

{ id: '2224', city: 'chicago', name: 'jon' },
{ id: '33', city: 'chicago', name: 'bill' }

我是否应该手动使用 switchMap 或其他东西来过滤结果?

我认为,使用 distinct() 不是适合您的用例的工具。您将得到一个完整的数组作为响应,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',但是,我不认为你想要这种类型的响应,在这里你会得到单个对象而不是数组。这意味着,您的订阅回调将被调用相同次数,内部可观察对象发出。

解法: 您可以自己过滤掉数组 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);
})