我如何在角度中设置组件功能的去抖动时间。 实际上,我从selectTableRow((方法中点击了一个api。当我选择 tr 然后点击 API 但是当我选择多个 tr 时,多个请求将进入服务器。
我希望当我快速选择多个表行时,只发送一个请求,例如(自动完成搜索(。
.HTML
<tr *ngFor="let data of tableData"
(click)="selectTableRows($event, data)"
[ngClass]="{'row-highlight': isRowSelected(data.id)}">
<td>
<span>{{data.name}}</span>
</td>
</tr>
方法
selectTableRows(event, rowData) {
//Hit api from here
}
这是不使用任何库的简单答案。
//define variable with null value
currentTimeout: any = null;
selectTableRows(event, rowData) {
//put your logic here
this.cancelTimeout();
this.currentTimeout = setTimeout(() => {
// call api from here
}, 1000);
}
cancelTimeout(): void {
clearTimeout(this.currentTimeout);
this.currentTimeout = undefined;
}
你可以试试这个。如果您有任何疑问,请告诉我。
要解决您的问题,请使用 lodash 库的去抖动方法。
npm i --save lodash
导入去抖动在 .ts 文件的顶部
import {debounce} from 'lodash';
像这样更新你的函数:
private debouncedFunction = null;
selectTableRows(event, rowData) {
if (this.debouncedFunction) {
this.debouncedFunction.cancel();
}
this.debouncedFunction = debounce(() => {
console.log('selectTableRows', rowData);
// make your API call here.
}, 2000);
this.debouncedFunction();
}
}