首页 > 解决方案 > 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或其他东西来过滤结果吗?

标签: angulargoogle-cloud-firestorerxjsdistinct

解决方案


我相信, 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);
})

推荐阅读