可选参数和子句.where

时间:2018-06-19 14:14:17

标签: typescript angular-cli angularfire2

我正在使用angularcliangularfire2,我的应用程序具有一种带有可选参数的方法,用于检索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();
    });
  }

1 个答案:

答案 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;
});