【问题标题】:Simple table filtering with RXJS and Angular使用 RXJS 和 Angular 进行简单的表格过滤
【发布时间】:2018-10-03 12:50:26
【问题描述】:

我正在尝试使用可过滤的表格。 我有这样的 ListComponent:

export class CompanyListComponent implements OnInit {
  companies$: Observable<Company[]>;
  private searchTerms = new Subject<string>();

  constructor(private companyService: CompanyService) { }

  ngOnInit() {
    this.companies$ = this.searchTerms.pipe(
        // wait 300ms after each keystroke before considering the term
        debounceTime(300),

        // ignore new term if same as previous term
        distinctUntilChanged(),

        // switch to new search observable each time the term changes
        switchMap((term: string) => this.companyService.searchCompanies(term)),
    );
}

search(term: string): void {
    this.searchTerms.next(term);
}

我的 html 看起来像这样:

<input #searchBox type="text" class="form-control" id="search-box" (keyup)="search(searchBox.value)">

<table class="table">
  <tr *ngFor="let company of companies$ | async">
    <td>{{company.name}}</td>
  </tr>
</table>

当我在搜索输入中写入时,表格会按应有的方式过滤。但是当我刷新页面时,表中根本没有数据。它出现在我在输入中输入内容之后。加载页面时我应该怎么做才能获取所有表格数据?我试图在 ngOnInit 中开始搜索,但这些尝试无济于事。

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    如果您希望在订阅时初始化链,您可以使用startWith

    this.companies$ = this.searchTerms.pipe(
      debounceTime(...),
      distinctUntilChanged(),
      startWith(''),
      switchMap(...)
    );
    

    【讨论】:

    • 不知道是什么意思
    • 不应该先入手吗?
    • 对不起,我也正要写你的答案,我正在构建一个我已经链接的示例
    • @ExplosionPills 您应该将所有答案合并为一个答案。
    【解决方案2】:

    searchTerms 更改为ReplaySubject(1) 并在构造函数中发出默认值。

       private searchTerms = new ReplaySubject<string>(1);
    
       constructor(private companyService: CompanyService) { 
              this.searchTerms.next('');
       }
    

    当页面刷新时,searchTerms 不会发出值,直到用户按下一个键。这意味着companies$ 在发出第一个搜索词之前什么都不做。

    使用回放主题允许您设置第一个值。

    【讨论】:

    • 为什么在这种情况下ReplaySubject 超过BehaviorSubject
    • @ExplosionPills 也可以,而且代码更少。
    猜你喜欢
    • 1970-01-01
    • 2020-07-12
    • 2018-05-23
    • 2015-06-03
    • 2018-12-13
    • 2016-10-25
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多