Angular 我想在上次更改延迟后触发onChange

Angular 我想在上次更改延迟后触发onChange,angular,input,timer,delay,Angular,Input,Timer,Delay,基本上,我有一个角度的应用程序,我想(改变)只有在几秒钟后才被触发。因此,不是每次在输入字段中写入一封信时都发送请求,而是在写入一封信后几秒钟内没有任何事情发生,然后将发送请求。您可以使用rxjsdebounceTime管道传输到反应式FormControl的valueChanges可观察值 逻辑是使用FormControl获取对输入的引用,并订阅valueChanges方法,并通过管道debounceTime仅在未在特定时间间隔内激发回调方法时激发回调方法 this.searchControl

基本上,我有一个角度的应用程序,我想(改变)只有在几秒钟后才被触发。因此,不是每次在输入字段中写入一封信时都发送请求,而是在写入一封信后几秒钟内没有任何事情发生,然后将发送请求。

您可以使用
rxjs
debounceTime
管道传输到反应式
FormControl
valueChanges
可观察值

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

this.searchControl.valueChanges
.pipe(
    debounceTime(2000),
    distinctUntilChanged()
)
.subscribe(res => {
    //your API call
});
这里的
distinctUntilChanged()
仅当发出不同的值时才执行订阅回调。


别忘了取消订阅…

退房。这正是你要找的。你需要的
debounce
你的两个答案都很好,但另一个答案也有distinctUntilChanged(),我认为这是一个更完整的答案。非常感谢。将答案更改为包含
distinctUntilChanged()
,这使订阅回调仅在发出不同值时执行。
  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...
          });