angular - 如何根据用户的输入即时过滤对象数组
问题描述
这应该很容易,但老实说,出于某种原因,它让我摸不着头脑。
基本上,我正在将来自 firestore 的数据查询到我的主要组件中,并且我正在根据用户输入过滤这些数据。
问题是我的搜索功能位于另一个组件中,因此我将查询的数据作为组件道具传递给搜索组件,并且我试图根据用户的输入对其进行过滤。
例如,如果用户键入“S”,它应该显示所有以 S 开头的项目,然后,“SP”会缩小范围,等等。
我不确定这样做是否是一个好主意,或者创建另一个查询并直接从 Firestore 过滤它。
我尝试做我正在做的事情的原因是因为它的读取成本更低,而且我不必再次查询数据。
我原来查询数据的方法是这样的:
在我的 search.ts
initiateSearch() {
if (this.searchTerm.length === 0) {
this.queryResult = [];
this.tempSearchStore = [];
}
const capitalizedsearchTerm = this.searchTerm.substring(0, 1).toUpperCase() + this.searchTerm.substring(1);
if (this.queryResult.length === 0 && this.searchTerm.length === 1) {
this.catService.searchCatalogs(this.searchTerm).then(snapShot => {
snapShot.forEach(cat => {
this.queryResult.push({ ...cat.data(), id: cat.id });
});
console.log('first', this.queryResult);
});
} else {
this.tempSearchStore = [];
this.queryResult.forEach(el => {
if (el.name.startsWith(capitalizedsearchTerm)) {
this.tempSearchStore.push(el);
}
});
console.log('temp', this.tempSearchStore);
}
}
和服务:
searchCats(searchFiled: string) {
const reference = this.afs.collection('blabla');
const query1 = reference.ref.where('searchKey', '==',
searchFiled.substring(0, 1).toUpperCase());
return query1.get();
}
有什么建议么?提前致谢。
解决方案
如果您使用以“S”开头的字符串查询所有文档,并且您启用了持久性,那么下一次查询具有以“SP”开头的字符串的文档将从缓存中提取结果,因为您是查询严格来说是您之前查询的内容的子集。在这种情况下,您将不会再为每个阅读付费。
推荐阅读
- discord.js - 如何不发送机器人消息编辑 discord.js
- javascript - 如何正确删除模态框内的内容
- linux - 为什么 Docker “在 $PATH 中找不到可执行文件 `/bin/sh`”?
- android - 无法解决::places-maps-sdk-3.1.0-beta:在 android 中集成 Google Maps v3.1.0 时
- xcode - 只能声明实例方法 @IBAction | XCODE 错误 | 斯威夫特 5
- i18next - i18next 返回文件根目录中的对象
- json - Swift - How to extract all values with same key names
- java - 单击按钮打开片段对话框时应用程序崩溃
- c++ - 不允许指向不完整类类型的指针 Unreal Engine 4.26
- php - 如何在 WP_Query 中为 category_name 使用“+”和“”?