abi*_*kay 4 javascript typescript angular
如何将去抖动时间添加到在表数据上搜索数据的动态搜索框?我在网站上查看了一些解决方案,但我的代码有点不同,我没有使用任何油门或其他东西,所以我很困惑。
我的模板代码:
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Search element">
Run Code Online (Sandbox Code Playgroud)
和打字稿是:
applyFilter(filterValue: string) {
this.tableDataSource.filter = filterValue.trim().toLowerCase();
}
Run Code Online (Sandbox Code Playgroud)
我想添加去抖动时间,以便每 2 秒进行一次搜索,而不是为每次更改发送大量请求。
提前致谢
我试图用管道从另一个方法调用该方法
filterData(filterValue: string) {
this.applyFilter(filterValue).pipe(debounceTime(2000))
}
Run Code Online (Sandbox Code Playgroud)
但现在它说,类型 void 上不存在管道
您正在对字符串使用管道运算符。您只能对 Observable 使用管道。Subject因此,您应该在组件中创建一个。Subject在 RxJS 中,它既充当 Observable 又充当观察者。换句话说,它会发出值并在值更改时监听该值。
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();
});
}
Run Code Online (Sandbox Code Playgroud)
当该applyFilter()方法在每次按键时调用时,Subject 都会发出 filterValue。在您的 中ngOnInit(),您应该收听/订阅您的主题,因此您可以使用pipe运算符 和debounceTime。
模板:
<input matInput (input)="terms$.next($event.target.value)" type="text"
placeholder="Search element">
Run Code Online (Sandbox Code Playgroud)
成分:
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
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5169 次 |
| 最近记录: |