首页 > 解决方案 > 我可以将连接字符串放入 AngularFire 的查询中吗?

问题描述

我正在尝试使用 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;
}

标签: angulartypescriptgoogle-cloud-firestoreangularfirequerying

解决方案


您将希望停止使用字符串来定义查询。要将字符串转换为可执行代码,您必须这样做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;
}

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


推荐阅读