내 프로젝트에 로컬로 저장된 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()
함수에서 잘못되었다는 것이지만, 나는 그것이 무엇인지 전혀 모른다.
파이프를 포함하지 않는 검색 및 필터링에 대한 다른 방법이 있습니까?
나는 충분히 이온을 모르는 반드시'filterLocations' 전에'load'를 호출해서는 안되는가요? 'data'가 없다면 이것은 예상 된 동작이 될 것입니다. – EdoPut