orderBy 管道无法正常工作

orderBy pipe doesn't works properly

我正在使用页面中的 ngx-pipes:

https://www.npmjs.com/package/ngx-pipes#orderby

我专门使用管道 orderBy,但是当我在我的 HTML 中使用 orderBy 管道时,信息没有正确排序(从小到大的顺序)。

我试着在被处理的对象中添加一个额外的 属性,这个被称为 diff 的 属性 是(lat 和 lng)TREATED PROPERTIES 的总和的结果,而不是原始的

并使用 属性 而不是同时使用 lat 和 lng 属性,但不起作用...

这是我的 home.page.html:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding">
    <p *ngFor = "let geo of absUserLocations | orderBy: ['lat', 'lng']">
      lat: {{geo.lat}}<br>
      lng: {{geo.lng}}<br>
    </p>
  </div>
</ion-content>

这是我的 home.page.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  public myCurrentLocation = {lat: 44.6, lng: 10.50};
  public absUserLocations = [];
  public userGeolocations = [];

  constructor() {

    this.userGeolocations = [
      {
        lat: 44.71620446490455,
        lng: 10.692454582877872
      },
      {
        lat: 44.63622591783756,
        lng: 10.575689162245453
      },
      {
        lat: 44.827688291479625,
        lng: 10.580959962491988
      },
      {
        lat: 44.618612858983525,
        lng: 10.650185180418703
      },
      {
        lat: 44.83988342851342,
        lng: 10.757238916147344
      }
    ];

    this.userGeolocations.forEach((userLocation)=>{

      this.absUserLocations = 
      this.absUserLocations.concat([this.getUsersDistance(userLocation)]);

    });

  }

  toGeoposition(str){let [lat, lng] = [...str.split(";")]; return {lat, lng}}

  getUsersDistance(destinyUserLoc){

    return {
      lat: Math.abs(this.myCurrentLocation.lat - destinyUserLoc.lat), 
      lng: Math.abs(this.myCurrentLocation.lng - destinyUserLoc.lng)
    }

  }

}

注意:我有两个位置数组对象并且我只迭代其中一个的原因是第二个数组 (absUserLocations) 将包含用户当前位置与其他用户的差值的绝对值计算位置,通过此计算,我可以使用 orderBy 管道显示用户位置周围最近的用户。

在我的真实项目中,显然我不会显示地理位置,但我制作了这段简短的代码以确认一切正常。

当我看到文档中的结果,计算每个对象的lat和lng之和并按顺序与其他对象进行比较时,我意识到顺序是错误的!,我只需要显示absUserLocations的信息从小到大排序...

这是我目前收到的订单:

orderBy 管道按预期方式处理您提供的数据,因为它将按纬度升序对数据进行排序,然后按经纬度排序(这实际上意味着按纬度排序,因为您所有的纬度都不同) .正如您在问题开头所写,您真正想要订购的是 lat diff + the lng diff。

<p *ngFor = "let geo of absUserLocations | orderBy: ['diff']">
this.absUserLocations = this.userGeolocations.map(loc => {
  const latDiff = Math.abs(this.myCurrentLocation.lat - loc.lat);
  const lngDiff = Math.abs(this.myCurrentLocation.lng - loc.lng);
  const diff = latDiff + lngDiff;
  return {lat: latDiff, lng: lngDiff, diff};
});