首页 > 解决方案 > 在 TS 中使用 Custom_Pipe

问题描述

我有这个管道:

@Pipe({
name: 'searchNomES'
})
export class SearchNomESPipe implements PipeTransform {

transform(uos: IUo[], name?: string,): IUo[] {

if (!uos) return [];
if (!name) return uos;
name = name.toLocaleLowerCase();
uos = [...uos.filter(uo => uo.nom.toLocaleLowerCase().includes(name))];
   return uos;

}
}

当我像这样在我的 html 中使用管道时,它工作正常:

<ng-container *cdkVirtualFor="let image of display | async | searchNomES : name " >
</ng-container> 

但我尝试在我的 component.ts 中使用管道。我试试这个:

<mat-form-field >
<input matInput  
(keyup)="applyFilter2($event.target.value)">    
</mat-form-field>

import { SearchNomESPipe } from '../../search-nomES.pipe';

constructor(private  espipe:  SearchNomESPipe) { }

ngOnInit() {this.display=this.markerservice.getGeos() }

applyFilter2(name : string) {
this.display = this.espipe.transform(this.display,name);
}

我的服务:

getGeos() { return this. 
database.list('ES').snapshotChanges().pipe(map(actions => {
return actions.map(a => {
const data = a.payload.val();
const key = a.payload.key;
return {key, ...data };

但我有这个错误:

uos.filter 不是函数或其返回值不可迭代

标签: angulartypescriptpipe

解决方案


您正在使用可观察对象,因此您的管道必须处理可观察对象并返回可观察对象。然后,您将async在视图中使用管道。将您的管道修改为:

transform(uos: Observable<IUo[]>, name?: string): Observable<IUo[]> {
  return uos.pipe(
    map(data => {
      if (!data || !name) return [];
      name = name.toLocaleLowerCase();
      return data.filter(uo => uo.title.toLocaleLowerCase().includes(name));
    })
  );
}

然后模板:

<ng-container *cdkVirtualFor="let image of filtered | async" >

TS:

display: Observable<IUo[]>;
filtered: Observable<IUo[]>;

ngOnInit() {
  this.display=this.markerservice.getGeos() 
}

applyFilter2(name : string) {
   this.filtered = this.espipe.transform(this.display,name);
}

演示


推荐阅读