Angular 在TS中使用自定义管道

Angular 在TS中使用自定义管道,angular,typescript,pipe,Angular,Typescript,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 =>

我有一根管子:

@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> 
但我有一个错误:

uos.filter不是函数或其返回值不可编辑

试着这样做:

 ngOnInit() {
    this.markerservice.getGeos().subscribe(resp: any[] => {
      this.display = this.espipe.transform(resp, name)
    })
  }

您使用的是可观察对象,因此管道必须处理可观察对象并返回可观察对象。然后,您将在视图中使用
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));
    })
  );
}
转换(uos:可观察,名称?:字符串):可观察{
回油管(
地图(数据=>{
如果(!data | |!name)返回[];
name=name.toLocaleLowerCase();
返回data.filter(uo=>uo.title.toLocaleLowerCase().includes(name));
})
);
}
然后是模板:

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

TS:

显示:可观察;
过滤:可观察;
恩戈尼尼特(){
this.display=this.markerservice.getGeos()
}
applyFilter2(名称:字符串){
this.filtered=this.espipe.transform(this.display,name);
}

到目前为止,您尝试了什么?我想在ts代码中使用自定义管道,而不是html。当我从字段(keypup)在mat中写入时,您何时调用
applyFilter2
此.markerservice.getGeos()返回什么?错误表明结果可能不是列表。谢谢,它可以工作!如何使用服务进行过滤?如果我理解正确,您所说的是。。。我再次提醒你,小心这些不纯的烟斗。如果你的应用程序变慢,可能是因为这个管道。或者你的意思是你想尝试在服务中使用一个函数来过滤,而不是使用管道?实际上,现在当你真正思考时,只要你只在TS文件中使用管道,就不会影响性能。我想我累了,没有好好思考,哈哈:D问题只在于你是否在模板中提供管道,因为它会经常被调用。现在,它只在输入更改时调用。所以你们都很好,就像我在回答中提供的一样!:)当管道只影响模型时,我的性能要好得多。现在在组件中,我有减速。我将转向按服务过滤
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" >
display: Observable<IUo[]>;
filtered: Observable<IUo[]>;

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

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