Проблема в сортировке значения JSON по убыванию - PullRequest
0 голосов
/ 20 марта 2019

Я работаю над проектом Angular, в котором я хочу шортить игроков playerCreditPoint в порядке убывания снизу json

0: {playerName: "Imran Tahir",  country: "Dolphins", playerCreditPoint: "1.50"}
1: {playerName: "xyx",  country: "Dolphins", playerCreditPoint: "6.50"}
2: {playerName: "abc",  country: "Dolphins", playerCreditPoint: "4.50"}
3: {playerName: "def",  country: "Dolphins", playerCreditPoint: "11.50"}
4: {playerName: "mno",  country: "Dolphins", playerCreditPoint: "10.50"}
5: {playerName: "pqr",  country: "Dolphins", playerCreditPoint: "9.50"}

, для этого я использую каналы

 <div class="all_players" *ngFor="let player of players | orderBy :player; let pIndex = index">

Но это не работает, поскольку выдает ошибку. Не удалось найти трубу 'orderBy' Angular

Ответы [ 2 ]

1 голос
/ 20 марта 2019

Angular по умолчанию не имеет OrderBy или конвейера фильтра: https://angular.io/guide/pipes#no-filter-pipe Но следующий фрагмент может помочь.Пожалуйста, добавьте свои собственные проверки типов, если элемент содержит строки или типы данных, отличные от arr.

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
    name: 'orderBy'
})
export class OrderBy implements PipeTransform {
    transform(array, orderBy) {
        // descending
        return Array.from(array).sort((item1: any, item2: any) =>
            this.comparator(item2[orderBy], item1[orderBy])
        );
    }

    comparator(a: any, b: any): number {
        if (parseFloat(a) < parseFloat(b)) {
            return -1;
        }
        if (parseFloat(a) > parseFloat(b)) {
            return 1;
        }

        return 0;
    }
}

Без углового соуса то, что вы ищете, по существу

const data = [
  { playerName: "Imran Tahir", country: "Dolphins", playerCreditPoint: 1.5 },
  { playerName: "xyx", country: "Dolphins", playerCreditPoint: 6.5 },
  { playerName: "abc", country: "Dolphins", playerCreditPoint: 4.5 },
  { playerName: "def", country: "Dolphins", playerCreditPoint: 11.5 },
  { playerName: "mno", country: "Dolphins", playerCreditPoint: 10.5 },
  { playerName: "pqr", country: "Dolphins", playerCreditPoint: 9.5 }
];

function orderBy(arr) {
  return arr.sort((item1: any, item2: any) => {
    return comparator(item2, item1);
  });
}

function comparator(a: any, b: any) {
  return a.playerCreditPoint - b.playerCreditPoint;
}

console.log(orderBy(data));

0 голосов
/ 20 марта 2019

Угловой не имеет orderBy трубы.

Кроме того, вы можете использовать ngx-order-pipe или Вы можете создать свою собственную трубу для сортировки.

Ссылка: https://www.npmjs.com/package/ngx-order-pipe

ИЛИ

Перейдите по этой ссылке для создания собственной трубы.

...