I can't sort data ionic v2 ,Plz help me


#1

I want sort data.distance.
data.dormi_lati or data.longitude can sort but data.distance can’t sort, Plz Help

load(){

if(this.data){
       return Promise.resolve(this.data);
   }
    return new Promise(resolve => {
    this.http.get('http://www.saintmansion.chiangmai-website.com/dormitory/show_dormi.php')
    .map(res => res.json()).subscribe(data => {
    this.data = this.applyHaversine(data);
    this.data.sort((locationA, locationB) => {
      return locationA.distance - locationB.distance;
    });
    resolve(this.data);
  });
});

}

public applyHaversine(locations){

Geolocation.getCurrentPosition().then((Position)=>{
  let usersLocation = {
      lat: Position.coords.latitude,
      lng: Position.coords.longitude
  };

  locations.map((location) => {
    let placeLocation = {
        lat: location.dormi_lati,
        lng: location.dormi_longi
    };

    location.distance = this.get_distance(
        usersLocation,
        placeLocation
    ).toFixed(2);

    location.time = Math.round(location.distance*120/80);
  });

});

return locations;

}
public get_distance(start, end){

    let lat1 = start.lat;
    let lon1 = start.lng;
    let lat2 = end.lat;
    let lon2 = end.lng;

    let dLat = this.toRad((lat2 - lat1));
    let dLon = this.toRad((lon2 - lon1));
    let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
    Math.sin(dLon / 2) *
    Math.sin(dLon / 2);
    let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    let d = 6371 * c;
    let z = d + d * 0.3;
    return z;

}

toRad(x){

  return x * Math.PI / 180;

}


#2

You are mixing imperative and reactive styles, which is a recipe for pain.

interface Location {
  dormi_lati: string;
  dormi_longi: string;
  distance?: number;
  time?: number;
}

applyHaversine(locations: Location[]): Promise<Location[]> {
  return Geolocation.getCurrentPosition().then((Position)=>{
    // do stuff
    return locations;
  });
}

cachedLocations: Promise<Location[]>;

getLocations(): Promise<Location[]> {
  if (!this.cachedLocations) {
    this.cachedLocations = this.http.get(url).toPromise()
      .then(rsp => rsp.json())
      .then(locs => this.applyHaversine(locs))
      .then(locs => locs.sort((loca, locb) => loca.distance - locb.distance);
  }
  return this.cachedLocations;
}