0

我有这个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"}
   ];

但我不断得到:

例外:./Gallery 类库中的错误 - 内联模板:22:39 导致:无法读取未定义的属性“类型”

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

我该如何解决这个问题?

4

1 回答 1

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);
}
于 2016-11-28T04:04:02.437 回答