如何在TypeScript中为输入搜索框添加去抖时间?

5

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

我的模板代码:

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

而 TypeScript 是为此而生的:

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

我希望为搜索添加防抖时间,以便每2秒进行一次搜索,而不是在每次更改时发送大量请求。
提前致谢。
我已经尝试使用管道从另一个方法调用该方法。
filterData(filterValue: string) {
    this.applyFilter(filterValue).pipe(debounceTime(2000))
}

但现在它显示:类型void上不存在管道


请看这个问题 - ConnorsFan
不,我认为它们不一样。 - abidinberkay
不,它们完全相同。 - Roberto Zvjerković
我已经尝试了你建议的答案,但是出现了“类型void上不存在pipe、subscribe、oberve”错误。我按照最后一部分的问题更新进行了尝试。 - abidinberkay
使用FormControl https://stackoverflow.com/questions/50732416/rxjs-distinctuntilchanged-with-keyup-event/50734973?noredirect=1#comment96296332_50734973 - Eliseo
3个回答

11

模板:

<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
  });
}

9
您正在对字符串使用管道运算符。您只能对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()方法被调用,主题会发出过滤值。在你的ngOnInit()中,你应该监听/订阅你的主题,这样你就可以使用pipe运算符和debounceTime


谢谢!不错的方式。 - Avi Siboni

3

只需使用lodash-decorators和lodash即可。

import { Debounce } from 'lodash-decorators';

class AnyClass {
  constructor() {
    ...
  }

  @Debounce(100)
  filterData(filterValue: string) {
    ...
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接