我需要对某些动作实施某种延迟执行。例如,当您输入搜索字符串并且在用户停止打印之前不希望搜索发送服务器请求时。类似于我们在Google等搜索引擎中看到的那种。用rxjs实现该功能的最佳方法是什么?
答案 0 :(得分:3)
创建一个<input [formControl]="control">
...
public control = new FormControl();
this.control.valueChanges
.pipe(
debounceTime(300),
distinctUntilChanged()
)
.subscribe((value: string) => {
// Do stuff with the value
}
);
并使用以下代码段监听更改:
Server timeout waiting for the HTTP request from the client.
别忘了退订;)
答案 1 :(得分:2)
您可以使用debounceTime运算符:
const textInput$ = fromEvent(this.yourInput.nativeElement, 'keyup');
textInput$.pipe(
debounceTime(500), // discard emitted values that take less than 500ms
switchMap(text => this.getSearch(text)) // getSearch is your request to the server
)
.subscribe();
答案 2 :(得分:0)