ALAN ENTEM
ALAN ENTEM

Reputation: 45

Use Custom_Pipe in TS

I have this 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;

}
}

It works fine when I use the pipe in my html like that:

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

But I try to use the pipe in my component.ts. I try this:

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

My service:

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 };

But I have this error:

uos.filter is not a function or its return value is not iterable

Upvotes: 1

Views: 283

Answers (2)

AVJT82
AVJT82

Reputation: 73357

You are working with an observable, therefore your pipe must handle an observable, and return an observable. You will then be using async pipe in view. Modify your pipe to:

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

Then template:

<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

Upvotes: 1

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try like this:

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

Upvotes: 0

Related Questions