Angular2 - 对记录进行分组时找不到管道



>我从API获取数据并将其返回到正常工作的视图中。但我发现很难按日期对数据进行分组。当我尝试时,出现此错误:The pipe 'groupBy' could not be found

管道.ts

import { Pipe, PipeTransform } from "@angular/core";
@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform{
  transform(value: Array<any>, field:string): Array<any> {
    if (value) {
      const groupedObj = value.reduce((prev, cur) =>{
        if(!prev[cur[field]]) {
          prev[cur[field]] = [cur]
        } else{
          prev[cur[field]].push(cur);
        }
        return prev;
      }, {});
      return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
    } else {
      return null;
    }
  }
}

查看.html

<ion-item *ngFor="let item of list | groupBy:'date_ph'" no-lines >
<ion-item>
<ion-icon name="calendar" item-start color="light"></ion-icon>
   <h2>Date</h2>
<ion-note color="dark" item-end>{{item.date_ph}} </ion-note>
</ion-item>
    </ion-item>

查看.ts

import { GroupByPipe } from '../../pipes/groupby/groupby';
import {Component, Pipe} from '@angular/core';
@Component({
  selector: 'page-view',
  templateUrl: 'view.html'
})

view.ts文件中,您导入了GroupByPipe

import { GroupByPipe } from '../../pipes/groupby/groupby';

它不适用于您的view.html文件

您必须在app.module.ts文件中声明它:

@NgModule({
  declarations: [
    GroupByPipe
  ],
})

或者,您可以将 GroupByPipe 作为 Swanand 导入到组件中建议:

@Component({ 
  selector: 'page-view', 
  templateUrl: 'view.html'
  providers : [GroupByPipe]
 }) export class NameComponent implements OnInit {
  constructor(private groupByPipe: GroupByPipe) {}
  ngOnInit() {
    // invoke groupByPipe here based on your logic
  }
}

您需要在组件中导入服务。

import { GroupByPipe } from '../../pipes/groupby/groupby';
import {Component, Pipe} from '@angular/core'; 
@Component({ 
selector: 'page-view', 
templateUrl: 'view.html'
providers : [GroupByPipe]
 })

如果它不起作用,请尝试将其添加到 module.ts 文件中。

最新更新