如何在 angular 中使用 lodash _.debounce

how to use lodash _.debounce in angular

我尝试在我的 angular 应用中使用 lodash 库中的函数 _.debounce。

我的代码:

   onKeyup(event) {
    if (event.length >= 3) {
      this.getCities(event);
    }
  }

  public getCities(namePrefix: any) {

    this.citiesSrv.getCities(namePrefix).toPromise().catch(err => console.log(err)).then(results => {
      this.options = results["data"].map(x => x.name + ", " + x.country);
    }
    ).then(test => {
      this.filteredOptions = this.myControl.valueChanges
        .pipe(
          startWith(''),
          map(value => this._filter(value))
        );
    })
  }

我想在 OnKeyup 函数中延迟调用 getCities。 什么是正确的方法?

谢谢

您需要将 debounce 包裹在 getCities 周围并调用它。所以在你的组件文件中 在下面的代码片段中,我将它去抖动到 400 毫秒

debouncedGetCitities = _.debounce(params => this.getCities(params), 400);
...
onKeyup(event) {
    if (event.length >= 3) {
      this.debouncedGetCitities(event);
    }
  }