Typescript debouncetime(2000)仍会立即触发搜索

时间:2019-06-15 00:49:10

标签: typescript angular7

我在实现OnInit,AfterViewInit的组件中具有以下方法。 trackFuzzySearchChanges位于AfterViewInit()中。无论设置多少去抖动时间,该方法都会立即执行,并执行loadData(),该数据执行WEB API getScreeningSummaries3()。请帮忙。谢谢。

ngAfterViewInit() {

  this.dataSource.totalRecords$.subscribe(r => {
    this.paginator.length = r;
    this.totalRecords = this.paginator.length;
  });

  this.dataSource.pageNumber$.subscribe(n => {
    this.pageNumber = n;
  });

  this.dataSource.pageSize$.subscribe(n => {
    this.pageSize = n;
  });

  this.trackFuzzySearchChanges();
  this.trackFilterChanges();
  this.trackSortChanges();
  this.trackPaginatorChanges();
}

trackFuzzySearchChanges() {
  merge(this.fuzzySearch.valueChanges)
    .pipe(
      tap(() => {
        debounceTime(2000), // fuzzy search changed when keyup for 2 sec in the mat-form-field
          distinctUntilChanged(),
          this.paginator.pageIndex = 0;
        this.loadData();
      })
    ).subscribe();
}

enter image description here

1 个答案:

答案 0 :(得分:0)

您正在debounceTime(2000)运算符回调中调用distinctUntilChanged()tap。它们应通过管道传输以产生实际效果。我也看不到使用merge运算符的任何意义,因为它用于turn multiple observables into a single onbservable,请尝试这种方式;

trackFuzzySearchChanges() {
  this.fuzzySearch.valueChanges
    .pipe(
      debounceTime(2000), // fuzzy search changed when keyup for 2 sec in the mat-form-field
      distinctUntilChanged(),
      tap(() => {
        this.paginator.pageIndex = 0;
        this.loadData();
      })
    ).subscribe();
}