我正在使用angularcli
和angularfire2
,我的应用程序具有一种带有可选参数的方法,用于检索firestore
中的数据。
buildWomen(id: string, sex?: string, age?: string): Observable<Humans[]> {
this.humanCollec = this.db.collection('human/' + id + '/women', ref => ref
.where('sex', '==', sex) //--this can be null
.where('age', '==', age); //--this can be null
return this.humamObersArray = this.humanCollec.valueChanges();
}
为了简化本示例,我仅显示2个参数,但在实际方法中,我有10个参数。最好的方法是检查它或忽略最后一个参数为null
更新:
... service.ts
...
humanCol: AngularFirestoreCollection<Human>;
humanObersArray: Observable<Human[]>;
...
buildHuman(id: string, sex?: string, age?: string, ethnicity?: string, height?: string, weight?: string, religion?: string){ //: Observable<Human[]>
//this.humanCol =
this.db.collection('human/'+id+'/women', ref => {
let retVal = ref as any;
if (sex != null) { retVal = retVal.where('sex', '==', sex) }
if (age != null) { retVal = retVal.where('age', '==', age) }
if (ethnicity != null) { retVal = retVal.where('ethnicity', '==', ethnicity) }
if (height != null) { retVal = retVal.where('height', '==', height) }
if (weight != null) { retVal = retVal.where('weight', '==', weight) }
if (religion != null) { retVal = retVal.where('religion', '==', religion) }
return retVal;
//return this.humanObersArray = this.humanCol.valueChanges();
});
}
答案 0 :(得分:1)
在工厂内部的ref上构建,检查参数是否存在:
this.humanCollec = this.db.collection(`human/${id}/women`, ref => {
let retVal = ref as any;
if (sex != null) { retVal = retVal.where('sex', '==', sex) }
if (age != null) { retVal = retVal.where('age', '==', age) }
...
return retVal;
});