我有一个输入要点,在这里我想显示一个自动完成的解决方案。我尝试使用RxJS控制HTTP请求的编号。我想做:HTTP请求仅在用户停止输入1秒钟后才开始。
我创建此代码:
of(this.inputBox.nativeElement.value)
.pipe(
take(1),
map((e: any) => this.inputBox.nativeElement.value),
// wait 1 second to start
debounceTime(1000),
// if value is the same, ignore
distinctUntilChanged(),
// start connection
switchMap(term => this.autocompleteService.search({
term: this.inputBox.nativeElement.value
})),
).subscribe((result: AutocompleteResult[]) => {
console.log(result);
});
问题是debounceTime(1000)
没有等待继续管道。 switchMap在每次键入事件后立即启动。
用户完成输入后如何等待1秒?
问题是您的链以of(this.inputBox.nativeElement.value).pipe(take(1), ...)
开头,因此好像您在每次按键时都在创建一个新的链(具有一个新的反跳计时器)。
相反,您应该只有一个链并将值推入其源:
const keyPress$ = new Subject();
...
keyPress$
.pipe(
debounceTime(1000),
...
)
...
keyPress$.next(this.inputBox.nativeElement.value);