用rxjs实现延迟执行

时间:2019-09-30 07:14:18

标签: angular rxjs

我需要对某些动作实施某种延迟执行。例如,当您输入搜索字符串并且在用户停止打印之前不希望搜索发送服务器请求时。类似于我们在Google等搜索引擎中看到的那种。用rxjs实现该功能的最佳方法是什么?

3 个答案:

答案 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)

您所描述的听起来像是经典的预输入功能。

我建议阅读有关debounceTime()运算符的信息。 Typeahead

这将停止接受其他请求,直到经过一定时间,然后再将您的请求通过。