1

在我的应用程序中,我遇到了与combineLatest操作员相关的奇怪行为。我通过在线演示重现了这个问题:

注意:请忽略这个demo中的这个业务逻辑,这不是很合理,我只是想在技术层面重现这个问题。

https://stackblitz.com/edit/angular-qcdslo?file=src/app/app.component.ts

  private testRequest() {
    this.pokemon$ = combineLatest(this.limit$, this.offset$)
      .pipe(
        map(data => ({limit: data[0], offset: data[1]})),
        switchMap(data => this.pokemonService.getPokemon(data.limit, data.offset)),
        map((response: {results: Pokemon[]}) => response.results),
      );
  }

这个方法使用 combineLatest 来组合两个 observables:limit$ 和 offset$。并向 API 发送请求,其中 limit 和 offset 的值只是 API 的参数。

我通过以下方法每 5 秒将计数器值增加 1:

let counter = 1
setInterval(() => {
  this.offsetControl.setValue(counter)
  counter++;
}, 5000)

最后,由于某种原因,我还需要按以下方式每隔 6 秒调用一次 testRequest 方法:

setInterval(() => {
  this.testRequest();
}, 6000) 

那么网络请求行为如下:

limit=5&offset=0
limit=5&offset=1  
limit=5&offset=0
limit=5&offset=2 
limit=5&offset=0
limit=5&offset=3  
...
limit=5&offset=0
limit=5&offset=n  

我不明白为什么limit=5&offset=0反复发生。谢谢你。

4

1 回答 1

0

每次 testRequest 执行时,您都在创建一个新的 observable,这不是您想要做的,每次您重新创建 observable 时,您都将在调用startsWith 时获得startsWith 值。

摆脱最新的组合,只需从表单控件中提取值。

https://stackblitz.com/edit/angular-droqf6?file=src/app/app.component.ts

于 2019-07-03T03:42:25.757 回答