角度自定义订单管道排序数组正确

问题描述:

我有一个自定义管道,该管道通过数字类型的prop对对象数组进行排序.

I have a custom pipe that orders an array of objects by a prop that is of type number.

使用管道的模板

<div *ngFor="let product of products | orderBy:'price'">

OrderByPipe

OrderByPipe

export class OrderByPipe  implements PipeTransform {
transform(array: any[], field: string): any[] {
array.sort((a: any, b: any) => {
  if (a[field] < b[field]) {
    return -1;
  } else if (a[field] > b[field]) {
    return 1;
  } else {
    return 0;
  }
});
return array;
}
}

当我使用forEach遍历每个项目时,管道似乎适用于较小的数组.但是,当我在最后对控制台进行控制台并在模板中将其返回时,该阵列仍处于混乱状态.

The pipe seems to work for smaller arrays and when I use forEach to loop through each item. However when I console the array at the end and when it is returned in the template, the array is still out of order.

我不确定是什么原因造成的,谢谢.

I am not entirely sure what might be causing this, thanks.

也许您根本不需要管道,而在组件中则需要服务

Maybe you dont need a pipe at all and you need a service ,in your component

originalProducts;
orderedProducts;

ngOnInit() {
    this.getProducts();
}

getProducts() {
  this.productsService.getProducts()
    .subscribe((data) => {
    this.originalProducts = data;
    this.sortBy('price');  
  });
}

sortBy(field: string) {

        this.originalProducts.sort((a: any, b: any) => {
            if (a[field] < b[field]) {
                return -1;
            } else if (a[field] > b[field]) {
                return 1;
            } else {
                return 0;
            }
        });
        this.orderedProducts = this.originalProducts;
}

在您的模板中

<div *ngFor="let product of orderedProducts">

如果您的列表太长,请使用分页.

And if your list is too long then use pagination.

如果仍然遇到问题,请使用lodash.

If still you have trouble, use lodash.

祝你好运!