使用解析数据的 Ionic 3 搜索过滤器

Ionic 3 Search Filter Using Parse Data

我正在尝试实现一个搜索栏,该搜索栏根据城市名称搜索用户的输入。 在我的 HTML 页面上,城市名称已经列出,但用户也可以选择搜索特定城市。 城市名称来自我在 Parse 中的数据库。

这是我的 HTML 代码:

<ion-searchbar (ionInput)="searchCities($event)"></ion-searchbar>

这是我的 .ts 代码,其中 citiesTotal 是一个变量,其中包含一个数组,该数组包含来自 Parse 的有关城市的数据:

searchCities(event) {

    var val = event.target.value;

    if (val && val.trim() != '') {
      this.citiesTotal= this.citiesTotal.filter((city) => {
        console.log(city.name);
        return (city.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
}

单击搜索栏后,我的控制台日志行成功检索到城市名称。但是,搜索栏本身不会过滤任何城市名称。

[更新]

我想我会包含更多代码来帮助解决这个问题,正如@SergeyRudenko 所建议的...

这是我的 .ts 代码,包括我从提供程序文件中提取数据的代码。 CityServ 是我的提供商文件。

constructor (private cityService: CityServ) {

    //this successfully retrieves the data I need
    if (this.cityService.all().length == 0) {
      this.cityService.getCities().then((success) => {
        this.cities = this.cityServ.all();
        this.citiesTotal = this.cities;
      }).catch((error) => {
        console.log('Error!');
      });
    } else {
      this.cities = this.cityService.all();
      this.citiesTotal = this.cities;
    }
}

searchCities(event) {

    var val = event.target.value;

    if (val && val.trim() != '') {
      this.citiesTotal= this.citiesTotal.filter((city) => {
        console.log(city.name);
        return (city.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
}

这是我的 .html 文件中的相关代码:

<ion-searchbar (ionInput)="searchCities($event)"></ion-searchbar>
<ion-list>
    <ion-item *ngFor="let item of items">
        {{city.name}}
    </ion-item>
</ion-list>

因此理想情况下,您还应该共享您的 cityService 提供程序代码,因为它可以具有从共享代码中看不到的其他上下文。

根据您分享的代码,我发现了 3 个问题:

searchCities 方法中的第一个特定问题 - 特别是在这一行中:

this.citiesTotal= this.citiesTotal.filter((city) => {...}

基本上,每次用户在搜索框中键入内容时,您都会将 this.citiesTotal 重新分配给其过滤后的子集。虽然理想情况下,您应该将作为搜索结果呈现给用户的内容与您的原始城市列表分开。

试试这个:

searchCities(event) {

    var val = event.target.value;

    if (val && val.trim() != '') {
      // here assign to "cities" instead of "citiesTotal":
      this.cities = this.citiesTotal.filter((city) => {
        return (city.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
}

现在你的ts代码应该有分离: - 在构造函数中初始化期间,您将数据分配给两个变量(cities 和 citiesTotal),但随后根据用户操作,您应该仅将更改应用到变量 "cities"。

第二个问题是您缺少用户重置搜索的逻辑。参见 official doc 的搜索栏,有一个特殊的侦听器:(ionCancel)="onCancel($event)"。在你的 ts 代码中你应该有这样的重置:

resetSearch(event) {
    this.cities = this.citiesTotal;
}

然后在您的模板中您需要添加 (ionCancel)="resetSearch($event)".

我在您的模板中看到的第三个问题是您的绑定未指向正确的项目:

<ion-searchbar showCancelButton="true" (ionInput)="searchCities($event) (ionCancel)="resetSearch($event)"></ion-searchbar>
<ion-list>
    // here ensure your ngFor is pointing to the right var:
    <ion-item *ngFor="let city of cities">
        {{city.name}}
    </ion-item>
</ion-list>

尝试解决所有这三个问题,如果您遇到困难,请告诉我。