使用管道进行全文搜索

时间:2016-12-09 10:28:45

标签: angular

是否可以使用管道在对象数组上创建全文搜索?

我开始实现搜索单个字段

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

但是得到以下错误

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

更新

组件

export class CustomerListComponent {

  public customers:any;

  constructor(
    private customerService: CustomerService) {
  }

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

模板

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

模块

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

1 个答案:

答案 0 :(得分:1)

它给你错误,因为最初没有为customers分配值,当你调用API时,结果可能是空的。

//组件

public customers:any[] = [];

//单索引搜索

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

//多索引搜索

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