【问题标题】:issue with debounceTime rxjs operator and http request on input keyup functiondebounceTime rxjs 运算符和输入 keyup 函数的 http 请求问题
【发布时间】:2019-08-19 14:25:42
【问题描述】:

我正在尝试在 angular7 中实现服务器端搜索。我找到了一些代码来实现这一点,但不幸的是这不能按要求工作。当我搜索一个字符串时,它会发送多个 http 请求,但它应该只是一个 http 请求。这是我的代码。

    fromEvent(this.simpleSearchInput.nativeElement, 'keyup').pipe(
      debounceTime(500),
      switchMap((search: any) => {
        return this.usersService.simpleUserSearch(search.target.value);
      })
    ).subscribe(res => {
      this.queryUsers = res.result.data;
      console.log('User Name is :' + res);

    }); 
  }

【问题讨论】:

  • 如果您在两次按钮单击之间使用超过 500 毫秒的时间,此代码将调用多个 http 请求,但我猜您已经意识到这一点。除此之外,据我所知,您的代码看起来是正确的。
  • 您正在尝试实现实时搜索,对吧?对于手动搜索,您可能希望收听表单提交事件。
  • @Kos 是的,我正在尝试实现实时搜索,我希望响应 keyup 或 input 事件。
  • @SnorreDan 我已将时间从 500 毫秒更改为 300 毫秒,但我遇到了同样的问题。我不知道它会如何工作。
  • 你需要增加它,而不是减少它。 300 只是 0.3 秒,所以这意味着如果用户在两次按钮点击之间使用超过 0.3 秒,就会发生 http 请求。例如,尝试将其设置为 2000,这意味着 2 秒。

标签: angular typescript http rxjs angular7


【解决方案1】:

这是一个粗略的示例,基于您的代码。记下日志记录并尝试使用 debounceTimedelay 的计时,看看它如何影响行为:

var { timer, fromEvent, of } = rxjs;
var { debounceTime, map, switchMap, delay, tap } = rxjs.operators;


var theInput = document.getElementById('the-input');

fromEvent(theInput, 'input').pipe(
  map(e=>e.target.value)     // read value from input
  , tap(console.info)        // realtime input log
  , debounceTime(1000)       // time till reaction
  // mocking long server request {{{
  , switchMap(q => of(q.toUpperCase()).pipe(
      tap(q => console.info('[requested]', q)),
      delay(2000),         // server ping time
      tap(q => console.info('[returned]', q))
  ))
  // }}}
).subscribe(res => {
  console.log('Result is: ' + res);
});
<script src="https://unpkg.com/rxjs@6.4.0/bundles/rxjs.umd.min.js"></script>

<input
  id="the-input"
  type="text"
  placeholder="Start typing"
  />

【讨论】:

  • 这不是一个答案,而是一个详细的操场示例来解释@SnorreDan 的含义
【解决方案2】:

这是我在某处找到的代码,它运行良好我使用 lodash 而不是使用 RXJS 库

步骤

1.在您的组件 ts 文件中导入 debounce。

从“lodash”导入 { debounce };

2。制作私有财产

private debouncedFunction: any = null;

3。在你的函数中使用 debouncedFunction

 search(event: any) {
    if (this.debouncedFunction) {
      this.debouncedFunction.cancel();
    }
    this.debouncedFunction = debounce(() => {
      console.log(event); // console.log will print event value after 1s of stop writing
    }, 1000);



 this.debouncedFunction();
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 2021-10-23
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    相关资源
    最近更新 更多