debounceTime rxjs运算符和输入keyup函数上的http请求的问题

时间:2019-03-28 17:50:12

标签: angular typescript http rxjs angular7

我正在尝试在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);

    }); 
  }

2 个答案:

答案 0 :(得分:0)

根据您的代码,这里有一个粗略的示例。记下日志记录并尝试使用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"
  />

答案 1 :(得分:0)

这是我在某处找到的代码,并且我使用lodash而不是RXJS库可以正常工作

步骤

1。在组件ts文件中导入反跳。

从“ lodash”导入{反跳};

2。成为私有财产

private debouncedFunction:任何= 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();
  }