【问题标题】:Can I make a concatenated string into a query for AngularFire?我可以将连接字符串放入 AngularFire 的查询中吗?
【发布时间】:2020-08-04 03:43:06
【问题描述】:

我正在尝试使用 Angular 8 在网站上制作动态搜索表单,用户可以使用不同的下拉菜单选择在 Firestore 中搜索的内容。根据不同的选择,我有一个函数可以生成一个与查询具有相同形式的字符串,尽管它是一个字符串。但是我不知道如何像我想的那样将它与valueChanges() 一起使用,因为它仍然是一个字符串。这可能吗?

我想这不是一种非常优雅(如果可能的话)进行动态查询的方法,但如果可能的话,我认为这会节省我目前的宝贵时间。 (我还看到了如何使用 BehaviourSubjects 和 switchMap 制作过滤器,所以如果这不起作用,我想这是另一种(更好的?)方法。)

async getRealTimeData(value) {
  this.query = await this.makeQuery(value);
  this.data = this.query.valueChanges();
}

async makeQuery(value) {
  var collection: string;
  switch (value.collection) {
    case 'X':
      collection = 'X';
      this.queryString = ".where('datetime', '>=', '2020-01-15T09:51:00.000Z')";
      break;
    case 'Y':
      collection = 'Y';
      this.queryString = ".orderBy('ID', 'asc')";
      break;
  }

  // If Z chosen, add to search string 
  if (value.Z) {
    this.queryString = this.queryString.concat(".where('Z', '==', value.Z)");
  }
  // If not viewAllUser, add list of permitted
  else if (this.authService.viewAllUser == false) {
    this.queryString = this.queryString.concat(".where('ID', 'in', this.permitted");
  }
  this.queryString = this.queryString.concat(".orderBy('datetime', 'desc')");
  // If realtime, add limit to search string
  // (If download: no limit)
  if (this.searchType == "realtime") {
    this.queryString = this.queryString.concat('.limit(100)');
  }

  this.query = this.query.concat(this.queryString).concat(')');
  console.log('Query: ',this.query);

  return this.query;
}

【问题讨论】:

    标签: angular typescript google-cloud-firestore angularfire querying


    【解决方案1】:

    您需要停止使用字符串来定义查询。要将字符串转换为可执行代码,您必须 eval() is,这在许多环境中都不是安全操作。但它也不是必需的,因为您也可以使用类似的模式来构建查询。

    async makeQuery(value) {
      switch (value.collection) {
        case 'X':
          this.query = this.query.where('datetime', '>=', '2020-01-15T09:51:00.000Z');
          break;
        case 'Y':
          this.query = this.query.orderBy('ID', 'asc');
          break;
      }
    
      // If Z chosen, add to query
      if (value.Z) {
        this.query = this.query.where('Z', '==', value.Z);
      }
      // If not viewAllUser, add list of permitted
      else if (this.authService.viewAllUser == false) {
        this.query = this.query.where('ID', 'in', this.permitted);
      }
      this.query = this.query.orderBy('datetime', 'desc');
      // If realtime, add limit to search string
      // (If download: no limit)
      if (this.searchType == "realtime") {
        this.query = this.query.limit(100);
      }
    
      return this.query;
    }
    

    您会看到代码仍然与您的非常相似,但现在构建的是实际查询,而不是连接字符串。

    【讨论】:

    猜你喜欢
    • 2015-11-27
    • 2023-03-30
    • 2021-11-13
    • 2016-03-03
    • 1970-01-01
    • 2012-01-02
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多