用户用RxJS完成键入后如何开始处理?

问题描述 投票:0回答:1

我有一个输入要点,在这里我想显示一个自动完成的解决方案。我尝试使用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秒?

rxjs rxjs6
1个回答
0
投票

问题是您的链以of(this.inputBox.nativeElement.value).pipe(take(1), ...)开头,因此好像您在每次按键时都在创建一个新的链(具有一个新的反跳计时器)。

相反,您应该只有一个链并将值推入其源:

const keyPress$ = new Subject();

...

keyPress$
  .pipe(
    debounceTime(1000),
    ...
  )

...

keyPress$.next(this.inputBox.nativeElement.value);
© www.soinside.com 2019 - 2024. All rights reserved.