如何在 Ionic 中实现搜索和过滤



我正在从存储在项目本地的 JSON 文件中获取数据。JSON 字符串是一个位置数组,其结构如下所示:

杰伦文件

{
    "locations": [
        {
            "title": "ABC",
            "latitude": -1.2596551,
            "longitude": 36.7066604,
            "routes":["22","23","105","115"],
            "fare":[],
            "matatu":[]
        },
        {
            "title": "Adams Arcade",
            "latitude": -1.3004204,
            "longitude": 36.7770793,
            "routes": ["2","4W","102","24","24C","111"],
            "fare":[],
            "matatu":[]
        },
        {
            "title":"Aga Khan Hospital",
            "latitude":-1.2620125,
            "longitude":36.8186399,
            "routes":["11A","11F","106","107","116"],
            "fare":[],
            "matatu":[]
        }
    ]
}

我没有使用管道动态过滤数据,而是在provider中实现了一个函数来处理这个问题。代码如下:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Geolocation } from '@ionic-native/geolocation';
@Injectable()
export class LocationProvider {
  data: any;
  constructor(public http: Http, public geolocation: Geolocation) {
  }
  load(){
    if(this.data){
      return Promise.resolve(this.data);
    }
    return new Promise(resolve => {
        this.http.get('assets/data/locations.json').map(res => res.json()).subscribe(data => {
          this.data = this.applyHarvesine(data.locations);
          this.data.sort((locationA, locationB) => {
            return locationA.distance - locationB.distance;
          });
          resolve(this.data);
        });
    });
  }
  filterLocations(searchTerm){
    return this.data.filter((location) => {
      return location.title.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
    });
  }
}

filterLocations()函数是接收searchTerm并返回一个仅包含与搜索条件匹配的元素的数组。

下面是呈现它的页面的.ts.html代码。

.ts

import { Component } from '@angular/core';
import { IonicPage, NavController } from 'ionic-angular';
import { LocationProvider } from '../../providers/location/location';
import { PlaceDetailsPage } from '../place-details/place-details';

@IonicPage()
@Component({
  selector: 'page-places',
  templateUrl: 'places.html',
})
export class PlacesPage {
  searchTerm: string = '';

  constructor(public navCtrl: NavController, public locations: LocationProvider) {
  }
  ionViewDidLoad() {
    this.setFilteredLocations();
  }
  setFilteredLocations(){
    return this.locations.filterLocations(this.searchTerm);
  }
}

。.html

<ion-content>
    <ion-searchbar [(ngModel)]="searchTerm" (ionInput)="setFilteredLocations()"></ion-searchbar>
    <ion-list no-lines>
        <button ion-item *ngFor="let location of locations.data">
            <ion-avatar item-left>
                <ion-icon name="pin"></ion-icon>
            </ion-avatar>
            <h2>{{location.title}}</h2>
            <p>{{location.distance}} km</p>
        </button>
    </ion-list>
</ion-content>

当用户在搜索栏上键入时,将调用setFilteredLocation()来触发数据筛选。问题是,什么都没有发生。

我哪里做错了?我的预感是setFilteredLocation()函数中有些不对劲,但我不知道它是什么。

是否有不涉及管道的替代搜索和筛选方法?

你做错了。

  1. 你做return this.data.filter(...).它对你的原点数组 ( this.data )。它只是返回一个新数组,不会对this.data进行更改。请参阅筛选器函数文档
  2. 如果要
  3. 更改数据,则需要添加:this.data = this.data.filter(...) 。但如果你这样做,你会陷入其他错误。您的this.data将在过滤器后丢失一些元素,并且在重置过滤器时无法恢复。

所以你应该这样做:
在组件中:

allData = []; //Store all data from provider
filterData = [];//Store filtered data
ionViewDidEnter(){
  this.allData = this.locations.data;
  this.filterData = this.allData;
}
setFilteredLocations(){
    this.filterData = this.allData.filter((location) => {
      return location.title.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
    });
}

在您的模板中使用过滤器数据ngFor

<button ion-item *ngFor="let location of filterData">

Yo 没有将$event发送到这里。因此,请尝试如下所示。

。.html

 <ion-searchbar [(ngModel)]="searchTerm" 
(ionInput)="setFilteredLocations($event)"></ion-searchbar>

.ts

 setFilteredLocations(ev: any){
    let val = ev.target.value;
    if (val && val.trim() !== '') {
      return this.locations.filterLocations(val);
    }
  }

您可以在此处查看官方示例代码

相关内容

  • 没有找到相关文章

最新更新