我在Angular项目中有这个方法:
getData(collection: string, field: string, operator: WhereFilterOp, value: string) {
return new Promise<any>((resolve, reject) => {
this.afs.collection(collection, ref => ref.where(field, operator, value)).snapshotChanges().subscribe(snapshots => {
resolve(snapshots);
})
})
}
它工作正常,但我的系统中有点我在查询中需要更多运算符,我真的不喜欢编写代码我想传递一个运算符数组来解决任何查询的单个方法我希望创建一个这样的方法:
getData(collection: string, query: FirestoreQuery[], value: string) {
return new Promise<any>((resolve, reject) => {
this.afs.collection(collection, ref =>
query.forEach(x => {
ref.where(x.field, x.operator, x.value);
})
).snapshotChanges().subscribe(snapshots => {
resolve(snapshots);
})
})
}
我创建了一个模型来简化运算符数组:
import { WhereFilterOp } from "@firebase/firestore-types";
export class FirestoreQuery {
field: string;
operator: WhereFilterOp;
value: string;
}
任何人都可以帮助创建此方法或向我展示为我的系统传递单个getData方法的运算符数组的其他方法。写代码很无聊。我需要专注于我的解决方案。
AskFirebase
答案 0 :(得分:0)
您可以使用化简函数组合查询。
import { WhereFilterOp } from '@firebase/firestore-types';
getData(collectionName: string, ...queries: any[]): Observable<any> {
const collection = this.db.collection(collectionName, ref => {
return queries.reduce((accumulator, query) => {
const [fieldPath, opString, value] = query;
return accumulator.where(fieldPath, opString as WhereFilterOp, value);
}, ref);
});
return collection.snapshotChanges();
}
// Usage
getData('sampleCollection', ['foo', '>', 0], ['foo', '<', 10]);