【问题标题】:DebounceTimer not working: Angular 2DebounceTimer 不工作:Angular 2
【发布时间】:2017-05-28 19:14:16
【问题描述】:

我在每次按键时都会进行 api 调用。以下是代码:

getResponse(Event) {

  this.responseService.getHttpResponse(this.searchInstance).debounceTime(5000).subscribe(.......);

据我了解,这不应该在每次按键时都进行 api 调用,而是在最后一次按键后等待 5 秒,然后获取结果。一种可能性可能是,因为我在去抖时间(正在进行 http 调用)之前调用了“getHttpResponse”,因此无论去抖时间如何,都会进行 http 调用。但这不应该在 5 秒之前获取结果。如果我的方法有问题,请纠正我。

【问题讨论】:

  • @yurzui 感谢您的帮助,但我并没有尝试缓存响应,而是尝试消除请求调用/响应的抖动。

标签: angular rxjs


【解决方案1】:
this.responseService.getHttpResponse(this.searchInstance).debounceTime(5000).subscribe(.......);

如果在 5 秒内发生按键操作,这不会取消新的 HTTP 调用。

相反,它会:
- 触发 HTTP 请求
- 等待 5 秒再继续
- 如果在这 5 秒内发出另一个请求,请不要将响应传递到 Observable 链中

但你想要的是:
- 等待 5 秒以确保不再发生击键
- 然后触发一个 HTTP 请求

为此,请阅读Thoughtram 上的精彩文章。

摘自文章
它可能看起来像这样:

export class App {

  items: Observable<Array<string>>;
  term = new FormControl();

  constructor(private wikipediaService: WikipediaService) {
    this.items = this.term.valueChanges
                 .debounceTime(400)
                 .distinctUntilChanged()
                 .switchMap(term => this.wikipediaService.search(term));
  }
}

【讨论】:

    猜你喜欢
    • 2016-10-15
    • 2018-12-02
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    相关资源
    最近更新 更多