首页 > 解决方案 > Angular 7:使用异步管道过滤多个键的搜索结果

问题描述

我想知道如何使用异步管道使用多个对象属性过滤搜索结果。目前,我可以根据 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>

标签: angularrxjs

解决方案


您可以修改该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;
     }))
   );

推荐阅读