angular - 以角度 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"
解决方案
使用 lodash 对名称进行排序
import {orderBy} from 'lodash';
case "Name": {
this.ProdData = orderBy(this.ProdData, ['Name'],['asc']);
}
case "Name1": {
this.ProdData = orderBy(this.ProdData, ['Name'],['desc']);
}
推荐阅读
- c - 我在判断问题的正确输出时遇到运行时错误
- typescript - 如何手动将 apollo 自定义标量映射到客户端类型
- ruby-on-rails - 使用 Rails 作为后端进行反应时,Fetch api 无法按预期工作
- c - 在线编译器(在线 gdb)正常工作,而 Windows 10 cmd 上的 g++ 和 gcc 在比较字符串时不起作用
- angular - 懒惰模块中的Angular ngx翻译不起作用
- java - 如何在主类内的方法中调用对象数组?
- html - 如何从页面 html 获取 facebook 发布时间戳/永久链接?
- json - 读取检索 json 文件而不在 laravel 7 中添加换行
- reactjs - React Router 更改了 URL 但页面仍然没有改变
- c++ - 在c ++中使用struct,无法解决问题