【问题标题】:Angular 7: Filter Search Results On Multiple Keys Using Async PipeAngular 7:使用异步管道过滤多个键的搜索结果
【发布时间】:2020-02-19 05:30:45
【问题描述】:

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

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 1970-01-01
      • 2019-04-07
      • 2019-04-10
      • 2017-09-30
      • 2017-03-27
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      相关资源
      最近更新 更多