首页 > 解决方案 > 以角度 8 对来自 get api 的数据进行排序

问题描述

我从 api 获取产品列表。我想根据我们的需要对产品进行排序,如下面的代码所示

我的 component.html

<select id="sort-by" (change)="sort($event)">
  <option value="" selected disabled hidden>Sort By</option>
  <option value="Name">Product list A-Z</option>
  <option value="Name1">Product list Z-A</option>
  <option value="Date">Date</option>
  <option value="Low">Show Low to High Price</option>
  <option value="High">Show High to Low Price</option>
</select>

我能够根据产品价格从低到高和从高到低对产品进行排序,但我无法对 AZ、ZA、日期的数据进行排序

我的 component.ts 文件

  ngOnInit() {
    this.productService.getProductList().subscribe((res: any) => {
      console.log(res.payload);
      this.ProdData = res.payload;
    });
  }

  sort(event: any) {
    switch (event.target.value) {
      case "Low": {
        this.ProdData = this.ProdData.sort(
          (low, high) => low.Price - high.Price
        );
        break;
      }

      case "High": {
        this.ProdData = this.ProdData.sort(
          (low, high) => high.Price - low.Price
        );
        break;
      }

      case "Name": {
        this.ProdData.sort(function (a, b) {
          if (a.Name < b.Name) {
            return 1;
          }
          if (a.Name > b.Name) {
            return -1;
          }
          console.log(a.Name);
        });
      }
      case "Name1": {
        this.ProdData.reverse();
      }
      case "Date": {
        this.ProdData.sort(function (c, d) {
          return c.UpdatedAt - d.UpdatedAt;
        });
      }

      default: {
        this.ProdData = this.ProdData.sort(
          (low, high) => low.Price - high.Price
        );
        break;
      }
    }
    return this.ProdData;
  }

我的 api 响应就像

     Id: 2
     Name: "cvcb1"
     Price: "20"
     Description: "bgfhjgj"
     CamparePrice: "78"
     SkuNumber: "568669"
     Quantity: "1"
     UpdatedAt: "2020-04-23T11:59:47.000Z"

标签: angular

解决方案


使用 lodash 对名称进行排序

import {orderBy} from 'lodash';
case "Name": {
this.ProdData = orderBy(this.ProdData, ['Name'],['asc']);
}
case "Name1": {
this.ProdData = orderBy(this.ProdData, ['Name'],['desc']);
}

推荐阅读