【发布时间】:2019-07-20 08:44:34
【问题描述】:
基本上,我有一个角度应用程序,我希望(更改)仅在几秒钟内没有发生任何事情后触发。因此,不是每次在输入字段中写信时都发送请求,而是在写完一封信并且几秒钟内没有任何事情发生后,才会发送请求。
【问题讨论】:
-
签出this answer。它正是您正在寻找的。span>
-
你需要
debounce
基本上,我有一个角度应用程序,我希望(更改)仅在几秒钟内没有发生任何事情后触发。因此,不是每次在输入字段中写信时都发送请求,而是在写完一封信并且几秒钟内没有任何事情发生后,才会发送请求。
【问题讨论】:
debounce
您可以使用 rxjs debounceTime 管道到反应性 FormControl 的 valueChanges 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(),这使得订阅回调仅在发出不同值时才会执行。
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...
});
别忘了取消订阅...
【讨论】: