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

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

我有一个输入元素,我想在其中显示自动完成的解决方案。我尝试使用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
2个回答
0
投票

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

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

const keyPress$ = new Subject();

...

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

...

keyPress$.next(this.inputBox.nativeElement.value);

0
投票

为什么不使用fromEvent创建流?

我发现没有必要使用distinctUntiChanged,因为input事件仅在发生更改时触发(即,用户添加/删除内容)。因此,流中的文本总是不同的。

const {fromEvent} = rxjs;
const {debounceTime, map} = rxjs.operators;

const text$ =
  fromEvent(document.querySelector('input'), 'input')
    .pipe(
      debounceTime(1000),
      map(ev => ev.target.value));

text$.subscribe(txt => {
  console.log(txt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js"></script>
<input/>
© www.soinside.com 2019 - 2024. All rights reserved.