我可以在AngularFire的查询中添加连接字符串吗?

问题描述 投票:0回答:1

我正在尝试使用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个回答
1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.