angular2 - 管道错误

时间:2016-11-28 03:37:23

标签: angular angular2-pipe

我有PipeGalleryFilter.ts

import { Pipe,Injectable,PipeTransform } from '@angular/core';
@Pipe({
    name: 'galleryfilter',
    pure: false
})
@Injectable()
export class PipeGalleryFilter implements PipeTransform {
    transform(items: any[], args: any[]): any {
        return items.filter(item => item.type.indexOf(args[0].type) !== -1);
    }
}///@@

然后我将其添加到我的Gallery

HTML

<masonry-brick class="brick50" *ngFor="let brick of bricks | galleryfilter: gallery_args">
  <img src="{{brick.img}}" alt="">
</masonry-brick>

TS

gallery_args = {type: 'magazine'};

bricks = [
     {title: 'Brick 1',img:"assets/img/img003.jpg",type: "magazine"},
     {title: 'Brick 2',img:"assets/img/img004.jpg",type: "magazine"},
     {title: 'Brick 3',img:"assets/img/img005.jpg",type: "newspaper"},
     {title: 'Brick 4',img:"assets/img/img003.jpg",type: "newspaper"},
     {title: 'Brick 5',img:"assets/img/img004.jpg",type: "newspaper"},
     {title: 'Brick 6',img:"assets/img/img005.jpg",type: "newspaper"},
     {title: 'Brick 1',img:"assets/img/img003.jpg",type: "movies"},
     {title: 'Brick 2',img:"assets/img/img004.jpg",type: "commercials"}, 
     {title: 'Brick 3',img:"assets/img/img005.jpg",type: "commercials"},
     {title: 'Brick 4',img:"assets/img/img003.jpg",type: "commercials"},
     {title: 'Brick 5',img:"assets/img/img004.jpg",type: "lifestyle"},
     {title: 'Brick 6',img:"assets/img/img005.jpg",type: "lifestyle"}
   ];

但我一直在接受:

  

EXCEPTION:./ Gallery类库中的错误 - 内联模板:22:39   造成:无法阅读财产&#39;类型&#39;未定义的

我有点怀疑它与行return items.filter(item => item.type.indexOf(args[0].type) !== -1);有关,但我不确定如何做到正确。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

由于gallery_args是一个对象(正如您在问题中所示),而不是array,因此gallery_args[0]当然不会被定义。

transform功能修改为:

transform(items: any[], args: any): any { // Note that the type of args should be any or {}
  return items.filter(item => item.type.indexOf(args.type) !== -1);
}