代码之家  ›  专栏  ›  技术社区  ›  Diego Venâncio

可选参数和子句。其中

  •  0
  • Diego Venâncio  · 技术社区  · 7 年前

    我在用 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

    更新 以下内容:

    …服务.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 回复  |  直到 7 年前
        1
  •  1
  •   James Daniels    7 年前

    基于工厂内的参考,检查是否存在参数:

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