我目前正在努力解决Ionic应用程序中看似简单的问题。我将BehaviorSubject
个GeoFire
个对象加载到客户端,根据它们与用户的距离关系(工作正常),然后在BehaviorSubject上执行订阅回调,我在其中分配一个数组'标记'到对象,然后根据它们包含的类别执行客户端过滤器并在DOM中列出它们。由于数据可能会按不同的类别进行多次过滤,因此会有一个markers
数组和一个filteredMarkers
数组,其中filteredMarkers
会在markers
开始时分配给filteredMarkers
每次调用过滤功能。
问题在于,当最初加载对象时,我的当前代码似乎在数据实际加载之前调用了此过滤函数,然后markers
被设置为ionViewDidLoad() {
console.log('ionViewDidLoad LocationsPage');
this.getUserLocation();
this.subscription = this.locationService.hits
.subscribe((hits) =>{
this.markers = hits;
this.filterLocations(this.locationCategory, this.markers)
},
(err)=> {
console.log(err);
});
}
private getUserLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
this.userLat = position.coords.latitude;
this.userLong = position.coords.longitude;
this.locationService.getLocations(this.radius, [this.userLat, this.userLong]);
console.log(this.locationService.hits);
});
}
}
filterLocations(category: string, markers) {
console.log(markers);
this.filteredMarkers = markers;
console.log('markers to be filtered: ', this.filteredMarkers, 'category: ',category);
if (category != ''){
category = category.toLocaleLowerCase();
this.filteredMarkers = this.filteredMarkers.filter(location => {
console.log(this.filteredMarkers);
return !category || location.category.toLowerCase().indexOf(category) !== -1;
});
}
return this.filteredMarkers;
}
在加载任何数据之前,从而产生一个空列表。如何确保数据已加载?这是我的代码:
页面组件:
getLocations(radius: number, coords: Array<number>) {
this.geoFire.query({
center: coords,
radius: radius
})
.on('key_entered', (key, location, distance) => {
console.log(newName);
let hit = {
location: location,
distance: distance,
name: '',
description: '',
category: ''
};
let currentHits = this.hits.value;
this.getLocationData(key).subscribe(
(location) =>{
newName = location.name;
hit.name = location.name;
hit.description = location.description;
hit.category = location.category;
currentHits.push(hit);
this.hits.next(currentHits);
}
);
});
}
getLocationData(ID: string): Observable<Location>{
return this.db.object('/locationData/'+ID).valueChanges();
}
LocationService:
spanTxt.length() -"Example".length()