angular2 - 管道错误

angular2 - pipe error

我有这个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: Error in ./Gallery class Gallery - inline template:22:39 caused by: Cannot read property 'type' of undefined

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

我该如何解决这个问题?

由于 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);
}