【问题标题】:How to add debounce time to in input search box in typescript?如何在打字稿的输入搜索框中添加去抖动时间?
【发布时间】:2019-02-20 12:57:12
【问题描述】:

如何将去抖动时间添加到搜索表格数据的动态搜索框?我在网站上查看了一些解决方案,但我的代码有点不同,我没有使用任何油门或其他东西,所以我很困惑。

我的模板代码:

<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Search element">

而打字稿是:

applyFilter(filterValue: string) {
    this.tableDataSource.filter = filterValue.trim().toLowerCase();
}

我想添加去抖动时间,以便每 2 秒进行一次搜索,并且不会为每次更改发送大量请求。

提前致谢

我尝试用管道从另一个方法调用该方法

filterData(filterValue: string) {
    this.applyFilter(filterValue).pipe(debounceTime(2000))
}

但现在它说,管道在 void 类型上不存在

【问题讨论】:

  • 看看this question
  • 不,我认为它们不一样。
  • 不,它们完全一样。
  • 我已经尝试过您建议的答案,但是管道,订阅,oberve 在类型 void 错误上不存在。我在上一部分的问题更新中尝试过。

标签: javascript angular typescript


【解决方案1】:

模板:

<input matInput (input)="terms$.next($event.target.value)" type="text" 
  placeholder="Search element">

组件:

private terms$ = new Subject<string>();

ngOnInit () {
  this.terms$.pipe(
    debounceTime(400), // discard emitted values that take less than the specified time between output
    distinctUntilChanged() // only emit when value has changed
  ).subscribe(term => {
    // do your search with the term
  });
}

【讨论】:

    【解决方案2】:

    您正在对字符串使用管道运算符。您只能对 Observable 使用管道。所以,你应该在你的组件中创建一个Subject。 RxJS 中的Subject 既充当 Observable 又充当 Observer。换句话说,它发出值并在值更改时侦听该值。

    private searchSub$ = new Subject<string>();
    
    applyFilter(filterValue: string) {
        this.searchSub$.next(filterValue)
    }
    
    ngOnInit() {
       this.searchSub$.pipe(
         debounceTime(400),
         distinctUntilChanged()
       ).subscribe((filterValue: string) => {
         this.tableDataSource.filter = filterValue.trim().toLowerCase();
       });
    }
    

    applyFilter() 方法在每次按键时调用时,Subject 会发出 filterValue。在您的ngOnInit() 中,您应该收听/订阅您的主题,因此您可以使用pipe 运算符和debounceTime

    【讨论】:

    • 谢谢!不错的选择。
    【解决方案3】:

    只需使用 lodash-decorators 和 lodash

    import { Debounce } from 'lodash-decorators';
    
    class AnyClass {
      constructor() {
        ...
      }
    
      @Debounce(100)
      filterData(filterValue: string) {
        ...
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-01
      • 2018-05-15
      • 2021-02-11
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多