在TS中使用Custom_Pipe

时间:2019-11-23 18:25:46

标签: 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 => 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不是函数或返回值不可迭代

2 个答案:

答案 0 :(得分:1)

您正在使用可观察对象,因此管道必须处理可观察对象,并返回可观察对象。然后,您将在视图中使用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);
}

DEMO

答案 1 :(得分:0)

尝试这样:

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