2017-10-16 1 views
1

내 프로젝트에 로컬로 저장된 JSON 파일에서 데이터를 가져옵니다. JSON 문자열은 그 구조가 매우 비슷 위치 어레이이다Ionic에서 검색 및 필터링을 구현하는 방법

JSON 파일 파이프와 즉석에서 데이터를 필터링하는 것은, 내 provider의 기능을 구현하기보다는

{ 
    "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":[] 
     } 
    ] 
} 

이것을 처리 할 수 ​​있습니다. 여기 코드는 다음과 같습니다

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 검색 창에 사용자가 입력, setFilteredLocation()는 데이터의 필터링을 트리거 호출

<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> 

.html 중에서

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); 
    } 

} 

. 문제는 아무 일도 일어나지 않는다는 것입니다.

어디로 잘못 갔습니까? 내 직감은 무엇인가가 setFilteredLocation() 함수에서 잘못되었다는 것이지만, 나는 그것이 무엇인지 전혀 모른다.

파이프를 포함하지 않는 검색 및 필터링에 대한 다른 방법이 있습니까?

+0

나는 충분히 이온을 모르는 반드시'filterLocations' 전에'load'를 호출해서는 안되는가요? 'data'가 없다면 이것은 예상 된 동작이 될 것입니다. – EdoPut

답변

1

잘못하고 있습니다.

  1. return this.data.filter(...) 원래 배열 (this.data)에는 아무런 영향을 미치지 않습니다. 그냥 새로운 배열을 반환하고 this.data로 변경하지 않습니다. 필터를 참조하십시오 function doc
  2. 데이터를 변경하려면 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에서의 FilterData를 사용

:

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

여기에 $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); 
    } 

    } 

당신은 official sample code here을 볼 수 있습니다.

+0

'ionViewDidLoad()'에 중첩 된'this.setFilteredLocations()'함수에서 어떤 인수를 주어야합니까? – mondieki

+0

필요하지 않습니다. 제거 할 수 있습니다. – Sampath

+0

나는 그것을 들여다 보았다. 작동하지 않습니다. 내가 놓친 게 있니? – mondieki

관련 문제