【问题标题】:Optional parameter and clausule .where可选参数和分句 .where
【发布时间】:2018-11-28 13:08:08
【问题描述】:

我正在使用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();
    });
  }

【问题讨论】:

    标签: typescript angular-cli angularfire2


    【解决方案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;
    });
    

    【讨论】:

    • 这种方式非常好。但是,关于:“查询类型不能分配给类型‘集合引用’。” { retVal = I try: let retVal: Query = ref but not working 中显示错误,并尝试删除 this.humanCollec ,但也不工作。
    • 这可能只是您将 retVal 重新分配为不同类型的类型系统不正常。将 retVal 转换为任何(或技术上的 CollectionReference | Query)
    • 编辑了我的答案以考虑到这一点。
    猜你喜欢
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多