首页 > 解决方案 > 如何在角度 5 的去抖时间上达到组件的功能?

问题描述

我如何以角度设置组件功能的去抖动时间。实际上我从 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
}

标签: angularangular5observabledebouncingdebounce

解决方案


要解决您的问题,请使用lodash库的 debounce 方法。

npm i --save lodash

在 .ts 文件顶部导入debounce

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

推荐阅读