Ansari Milah Ibrahim Ansari Milah Ibrahim - 14 days ago 5
Javascript Question

Using a Pipe with undefined startup values

In my pipe file i have this code

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {

transform(service: any, term: any): any {
if (term=== undefined) return service.filter(function(service){
return service.product_name.toLowerCase().includes("rustic".toLowerCase());
})

return service.filter(function(service){
return service.product_name.toLowerCase().includes(term.toLowerCase());
})
}
}


i call above pipe in this template :

<div class="searchresult" *ngFor="let service of services |search:term ">
<div [routerLink]="['/searchresult',service.product_name]" class="searchitem">ID : {{ service.product_name }}</div><br>
</div>


how to know that
service
not ready yet. Because in my application i want to search data from remote rest API (in my VPS hosting). currently i need to wait about 30 seconds before type the keyword to be passed to Pipe. if i type it before 30 seconds, mostly search will failed with return
Cannot read property 'filter' of undefined
. This is because rest API not be loaded yet to service. how to know that my service not already loaded so i can hold the search input to be disable until service ready to used...

every help will be really respected....

Answer

Sounds like your variable services is undefined at startup? Maybe set it to an empty array [] on application start..

However, change your Pipe like this to make it more robust against failures!

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {

  transform(services: any[], term: any): any {
    if (!services || !services.length) return []; // check inputs first!
    if (term === undefined) term = "rustic".toLowerCase();

    return service.filter(srvc => srvc.product_name.toLowerCase().includes(term.toLowerCase()))
  }
}
Comments