为多个字段的firestore查询连接两个可观察对象



我试图在我的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。只有第一个可观察对象被使用。我想我不理解concat操作符,但根据文档,我不清楚当前最好的解决方案是什么。

您可以使用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

这只适用于名字的原因是concat的工作方式;它一次只使用一个可观察对象,直到它完成,但是firestore的可观察对象是长期存在的,不会完成。

你应该用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);
}

最新更新