【发布时间】:2017-10-08 07:25:41
【问题描述】:
我对 Angular 2 还很陌生。那么请有人帮我在 Angular 2 中创建自定义管道吗?
我尝试了以下更改
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'groupTransactions'})
export class GroupTransactionsPipe implements PipeTransform {
transform(transactions: Array): Array {
const grouped = transactions.reduce( (grouping, item) => {
let month = new Date(item.date).getMonth()+1 ;
grouping[month] = grouping[month] || [];
grouping[month].push(
{
id: item.id,
name: item.name,
price: item.price
date: item.date
}
);
return grouping;
}, {} )
// 'grouped' is an object with properties keyed on date
// and each property value is an array of items
const result = Object.keys(grouped)
.map(key => {
const val =
{
date: key,
items: grouped[key] // can sort here by price or name
};
return val;
})
.sort(function (a, b) {
return b.date - a.date;
});
// Object.keys makes an array
// so now we have an array of objects
// each with a date property and an items property
// which is an array of objects (as shaped above)
// and finally sort on date
return result
}
}
但是错误的日期是 1970 年 1 月而不是 2017 年 9 月。目前我们正在按日期分组,但我想要按月分组。简而言之,如果交易放在同一个月的不同日期,它们应该归类在九月份。那么在自定义管道中获取 groupByMoth 需要进行哪些更改。所以我会得到如下输出:
September 17
product 11 £15.00
product 22 £15.00
19 Sep 2017
product 11 £15.00
product 22 £15.00
17 Sep 2017
August 17
product 11 £15.00
product 22 £15.00
20 Aug 2017
product 11 £15.00
product 22 £15.00
04 Aug 2017
July 17
product 33 £10.00
product 44 £20.00
January 16
product 66 £10.00
product 77 £20.00
您能帮忙实现吗?
【问题讨论】:
标签: angular typescript angular2-pipe