angular - 我可以将连接字符串放入 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;
}
解决方案
您将希望停止使用字符串来定义查询。要将字符串转换为可执行代码,您必须这样做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;
}
您会看到代码仍然与您的非常相似,但现在构建实际查询,而不是连接字符串。
推荐阅读
- python-3.x - 降低 float 和 int 的精度
- python - 按子页面日期排序的列表
- database - Oracle 数据库 - 从固定长度的文件中删除记录
- mocking - 是否可以在 x-faker 属性中使用具有最小值和最大值的 random.number 来进行 openapi 模拟
- java - ViewHolder 字段在 Fragment 中被初始化为 null
- python - 从场景方面来看,websocket 和烧瓶流有什么区别
- angularjs - 谷歌闭包编译器构建给出错误未处理标志:outputManifest'
- azure-iot-hub - 使用 IoT DevKit 和 Azure IoT Hub 向设备发送云消息 - 设备代码
- javascript - 在 HTML 页面上显示多个图表?
- html - 使图像在单击时打开模式?