Angular 7:使用异步管道过滤多个键上的搜索结果

时间:2019-10-23 03:03:52

标签: angular rxjs

我想知道如何使用异步管道使用多个对象属性来过滤搜索结果。目前,我可以根据name属性进行过滤并显示过滤后的结果,但是我也希望能够在username属性上进行搜索。这是我到目前为止的内容: 在我的TS文件中:

  public formSetup = this.fb.group({
    formSearch: new FormControl('')
  })

  constructor(private service: Service,
              private fb: FormBuilder) { }

  ngOnInit(): void {
   this.getFilters();
  }

  public getFilters() {

    const filter = (val: string): Observable<Array<object>> => {

      return this.service.getItems()
        .pipe(
          map(response => response.filter(option => {
            const value = `${option.name}`
            return value.toLowerCase().indexOf(val.toLowerCase()) === 0;
          }))
        );

    }

    this.filteredItems = this.formSetup.get('formSearch').valueChanges
      .pipe(
        startWith(null),
        debounceTime(200),
        distinctUntilChanged(),
        switchMap(val => {
          return filter(val || '');
        })
      );
  }

在我的HTML文件中:

  <input type="text" formControlName="formSearch">
</div>

<search [items]="filteredItems"></search>

最后,在我的组件中显示结果:

<search-card *ngFor="let item of (items | async ); trackBy:trackingFn" [items]="item"></search-card>

1 个答案:

答案 0 :(得分:0)

您可以修改filter()方法以同时搜索username属性。

return this.service.getItems()
  .pipe(
     map(response => response.filter(option => {
       const value = `${option.name}`;
       const username = `${option.username}`;
       return value.toLowerCase().indexOf(val.toLowerCase()) === 0 ||
         username.toLowerCase().indexOf(val.toLowerCase()) === 0;
     }))
   );