首页 > 解决方案 > 如何根据用户的输入即时过滤对象数组

问题描述

这应该很容易,但老实说,出于某种原因,它让我摸不着头脑。

基本上,我正在将来自 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();
}

有什么建议么?提前致谢。

标签: angularfirebasegoogle-cloud-firestore

解决方案


如果您使用以“S”开头的字符串查询所有文档,并且您启用了持久性,那么下一次查询具有以“SP”开头的字符串的文档将从缓存中提取结果,因为您是查询严格来说是您之前查询的内容的子集。在这种情况下,您将不会再为每个阅读付费。


推荐阅读