【问题标题】:Concat two observables for firestore query on multiple fields连接两个 observables 以在多个字段上进行 firestore 查询
【发布时间】:2021-02-20 21:21:46
【问题描述】:

我正在尝试在我的 AngularFire 应用中使用用户搜索功能。 由于firestore不支持这些查询,我认为单独查询字段就足够了

getUsersByName(searchValue: string) {
    const firstNames = this.afs.collection<IUser>('user', ref => ref.orderBy('firstname').startAt(searchValue).endAt(searchValue+'\uf8ff')).valueChanges({ idField: 'id' });
    const lastNames = this.afs.collection<IUser>('user', ref => ref.orderBy('lastname').startAt(searchValue).endAt(searchValue+'\uf8ff')).valueChanges({ idField: 'id' });
    return concat(firstNames, lastNames);
  }

这仅适用于firstNames。只有第一个 Observable 被使用。我想我不了解 concat 运算符,但根据文档,我不清楚当前针对此问题的最佳解决方案是什么。

【问题讨论】:

    标签: google-cloud-firestore rxjs observable angularfire


    【解决方案1】:

    你可以使用 zip 运算符

    const firstNames: Observable<string>
    const lastNames: Observable<string>
    zip(firstNames,lastNames).subscribe(
      ([firstName,lastName]) => { console.log(firstName,lastName);}
    )
    

    如果 firstNames 和 lastNames 只发出一个项目, combineLatest([firstNames,lastNames]) 将更具可读性

    了解如何使用这些运算符的好链接https://indepth.dev/posts/1114/learn-to-combine-rxjs-sequences-with-super-intuitive-interactive-diagrams

    【讨论】:

    • 感谢您提供有用的链接。将我的回报改为return zip(firstNames, lastNames);没有用,我没有得到任何结果
    【解决方案2】:

    这仅适用于名字的原因是concat 的工作方式;在完成之前,它一次只会使用一个 observable,但 firestore observable 的寿命很长,不会完成。

    您应该使用merge 而不是concat

    import { merge } from 'rxjs';
    
    getUsersByName(searchValue: string) {
        const firstNames = this.afs.collection<IUser>('user', ref => ref.orderBy('firstname').startAt(searchValue).endAt(searchValue+'\uf8ff')).valueChanges({ idField: 'id' });
        const lastNames = this.afs.collection<IUser>('user', ref => ref.orderBy('lastname').startAt(searchValue).endAt(searchValue+'\uf8ff')).valueChanges({ idField: 'id' });
        return merge(firstNames, lastNames);
      }
    

    【讨论】:

    • 我试过这个return firstNames.pipe(merge(lastNames)); 但没有成功。我看到了 firstNames 的结果,但之后我的测试都没有返回结果
    • 您使用了merge 运算符而不是静态合并函数。我在上面的答案中添加了示例。
    • 感谢您的更新。尽管如此,它仍然表现得很奇怪,在订阅中我收到了多个事件,所以看起来订阅分别在两个 Observables 上,而我希望它表现为单个 Observable..
    • 是的,merge 就是这样工作的,它会在任何源 observable 发出时发出,但对于getUsersByName() 的消费者来说,它是一个单独的 observable。你想要的输出是什么?
    • 我希望我的搜索操作也只有一个发射,这可能吗?
    猜你喜欢
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2023-01-22
    • 1970-01-01
    • 2019-10-25
    • 2014-06-15
    • 1970-01-01
    相关资源
    最近更新 更多