【问题标题】:search by text and update Observable<Array[]> Angular 7按文本搜索并更新 Observable<Array[]> Angular 7
【发布时间】:2019-05-17 22:28:58
【问题描述】:

我需要帮助。 我是 Angular 的新手,我正在使用 Angular 7,最新版本。

所以我的 Html 代码:

<input type="text" class="form-control" (input)="onSearchChange($event.target.value)" placeholder="Search serial...">

我的组件.ts

  onSearchChange(searchValue: string) {
    //alert(searchValue);
    console.log(searchValue);
    this.filteredItems = this.listaTest; //uno un array di appoggio per la ricerca real-time
    this.filteredItems.subscribe(
      (response) => {
        console.log(response);
        this.filteredItems = response.filter(x => x.seriale.startsWith(searchValue));
        });
  }

我的&lt;ul&gt;名单:

<ul class="list-group" style="width:80%; margin:0 auto; font-weight: bold; margin-top: 2%;">
  <li *ngFor="let item of filteredItems | async" class="list-group-item">{{item.seriale}}
  <button style="float:right;">{{item.seriale}}Download certificati</button>
  </li>
</ul>

我的目标是在用户搜索时实时更新&lt;ul&gt; 列表。 所以我尝试了一个数组,而不是 Observable,我只是推动并删除并完成。 但是,使用 Observable,我如何实时更新列表?和过滤一样吗? 谢谢

【问题讨论】:

    标签: angular filter rxjs observable angular7


    【解决方案1】:

    在ts文件中,可以结合搜索流和列表流得到结果流。

    // a stream of search keyword
    const search$ = new Subject();
    
    const refineSearch$ = search$.pipe(
      // you can filter out empty string if you want
      filter(keyword => keyword !== ''),
      // avoid to many work by debounceTime
      debounceTime(500),
    )
    
    // here use of for demonstration
    // if your list is changing over time
    // its should be a list of stream
    const list$ = of(aListOfItem);
    
    const result$ = combineLatest(refineSearch$, list$)
      .pipe(map(([keyword, list]) => getSearchResult(keyword, list)));
    
    function getSearchResult(keyword, list) {
      // implement your filter
      // return an array
    }
    

    在模板中,输入事件将简单地生成下一个值来搜索流。

    <input type="text" class="form-control" (input)="search$.next($event.target.value)" placeholder="Search serial...">
    

    ul变化不大,只是将filteredItems替换为result$stream

    <ul class="list-group" style="width:80%; margin:0 auto; font-weight: bold; margin-top: 2%;">
      <li *ngFor="let item of result$ | async" class="list-group-item">{{item.seriale}}
      <button style="float:right;">{{item.seriale}}Download certificati</button>
      </li>
    </ul>
    

    【讨论】:

      猜你喜欢
      • 2017-12-16
      • 2018-03-04
      • 1970-01-01
      • 2019-06-06
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 2014-07-31
      相关资源
      最近更新 更多