分组数据管道不起作用

时间:2018-07-27 15:08:48

标签: html angular pipe grouping

我正在尝试使该组管道正常工作,但是html似乎有错误。错误消息:TypeError:无法读取未定义的属性'forEach'。当我找到错误时,似乎是html上的一行出现了问题。

JSON:

[
{
    "month": "2017-03-01",
    "modelVolume" [{
           "id": 1,
           "model": P213
    }]
}
{
    "month": "2017-03-01",
    "modelVolume" [{
           "id": 1,
           "model": P213
    }]
}
{
    "month": "2017-03-01",
    "modelVolume" [{
           "id": 1,
           "model": P213
    }]
}
{
    "month": "2017-03-01",
    "modelVolume" [{
           "id": 1,
           "model": P213
    }]
}
{
    "month": "2017-03-01",
    "modelVolume" [{
           "id": 1,
           "model": P213
    }]
}
{
    "month": "2017-03-01",
    "modelVolume" [{
           "id": 1,
           "model": P213
    }]
}
{
    "month": "2017-03-01",
    "modelVolume" [{
           "id": 1,
           "model": P213
    }]
}
{
    "month": "2017-03-01",
    "modelVolume" [{
           "id": 1,
           "model": P213
    }]
}
{
    "month": "2017-03-01",
    "modelVolume" [{
           "id": 1,
           "model": P213
    }]
}]

这似乎是问题所在的HTML代码:

       <ul>
            <li *ngFor="let group of volumes | GroupByPipe">{{group.month}}
              <ul>
                <li *ngFor="let event of group.modelVolumes">{{event.id}} {{event.model}}</li>
              </ul>
            </li>
        </ul>

这是管道:

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

@Pipe({name: 'GroupByPipe'})
export class GroupByPipe implements PipeTransform {
    transform(collection: Array<any>, property: string = 'month'): Array<any> {
        if(!collection) {
            return null;
        }
        const gc = collection.reduce((previous, current)=> {
            if(!previous[current[property]]) {
                previous[current[property]] = [];
            }
                current.volumes.forEach(x => previous[current[property]].push(x));
            return previous;
        }, {});
        return Object.keys(gc).map(volume => ({ month: volume, modelVolumes: gc[volume] }));
    }
}

0 个答案:

没有答案