【问题标题】:I want to trigger onChange after a delay from last change我想在上次更改延迟后触发 onChange
【发布时间】:2019-07-20 08:44:34
【问题描述】:

基本上,我有一个角度应用程序,我希望(更改)仅在几秒钟内没有发生任何事情后触发。因此,不是每次在输入字段中写信时都发送请求,而是在写完一封信并且几秒钟内没有任何事情发生后,才会发送请求。

【问题讨论】:

  • 签出this answer。它正是您正在寻找的。​​span>
  • 你需要debounce

标签: angular input timer delay


【解决方案1】:

您可以使用 rxjs debounceTime 管道到反应性 FormControlvalueChanges observable,如 https://stackblitz.com/edit/angular-debounce-form-control 的示例中所示

逻辑是使用FormControl 获取对您的输入的引用并订阅valueChanges 方法并通过管道传递debounceTime 以仅在未在特定时间间隔内触发回调方法时触发。

this.searchControl.valueChanges
.pipe(
    debounceTime(2000),
    distinctUntilChanged()
)
.subscribe(res => {
    //your API call
});

这里distinctUntilChanged() 使订阅回调仅在发出不同值时才执行。

【讨论】:

  • 你的两个答案都很棒,但另一个也有 distinctUntilChanged() 我认为这是一个更完整的答案。非常感谢。
  • 将答案更改为包含distinctUntilChanged(),这使得订阅回调仅在发出不同值时才会执行。
【解决方案2】:

https://stackblitz.com/edit/angular-rwrinz-sxjtfj

  this.control.valueChanges
          .pipe(
            debounceTime(1000), // Waiting for 1 sec while you are typing
            distinctUntilChanged() // Prevents the emitting if the 'start' value and the 'end' value are the same
          )
          .subscribe(value => {
            console.log(value);
            // TODO: call BE here with this.httpClient...
          });

别忘了取消订阅...

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2023-03-19
    • 2023-01-11
    • 1970-01-01
    • 2013-07-07
    相关资源
    最近更新 更多