robert
robert

Reputation: 857

Fulltext search with pipe

Is it possible to create a fulltext search over an array of objects with a pipe?

I start with implementing a search for a single field

export class SearchPipe implements PipeTransform {
    transform(value: any): any {
      return value.filter((item) => item.company.startWith('s'));
    }
}

But get the following error

core.umd.js:3488 EXCEPTION: Uncaught (in promise): Error: Error in ./CustomerListComponent class CustomerListComponent - inline template:17:20 caused by: Cannot read property 'filter' of undefined
TypeError: Cannot read property 'filter' of undefined

Update

Component

export class CustomerListComponent {

  public customers:any;

  constructor(
    private customerService: CustomerService) {
  }

  ngOnInit() {
    this.customerService.getCustomers()
      .subscribe(data => this.customers = data)
  }
}

Template

<tr *ngFor="let customer of customers | search">
    <td>{{customer.id}}</td><td><a [routerLink]="['/profile', customer.id]">{{customer.company}}</a></td>...
</tr>

Module

@NgModule({
  imports:      [ BrowserModule, HttpModule, routing ],
  declarations: [ AppComponent, CustomerListComponent, CustomerProfileComponent, SearchPipe ],
  bootstrap:    [ AppComponent ]
})

Upvotes: 2

Views: 1891

Answers (1)

ranakrunal9
ranakrunal9

Reputation: 13558

Its giving you error because there is no value assigned to customers initially and when you call API may be results are empty.

// Component

public customers:any[] = [];

// Single index search

export class SearchPipe implements PipeTransform {
  transform(value: any): any {
    return (typeof value !== 'undefined') ? value.filter((item) => item.company.startWith('s')) : true;
  }
}

// Multiple index search

export class SearchPipe implements PipeTransform {
  transform(value: any): any {
    return (typeof value !== 'undefined') ? value.filter((item) => {   
      return item.company.startWith('s') || item.company_name.startWith('s') || item.another_index.startWith('s');
    }) : true;
  }
}

Upvotes: 1

Related Questions