【问题标题】:switchMap: Multiple (2) requests getting triggeredswitchMap:多个 (2) 请求被触发
【发布时间】:2016-08-03 22:11:05
【问题描述】:

我正在使用 Angular 2 RC-4。每当输入框中发生更改时,我都会尝试发出网络请求。但是请求被调用了两次。

我的代码如下:

component.ts

this.term = new Control();

this.suggestions = this.term.valueChanges
      // .debounceTime(1000)
      // check if the search term's length is >= 1
      .filter(term => term && term.length)

      // switchMap only subscribes to one observable at a time so if a new key is
      // pressed before the response of previous request has been recieved, it
      // automatically un-subscribes from the previous observable thus cancelling the previous
      // request.
      .switchMap(term => this._suggestionsService.getSuggestions(term, uuid))

component.html

<ul [hidden]='!(suggestions | async)?.length'>
<li *ngFor='let suggestion of suggestions | async'>{{suggestion.name}}</li>
</ul>

suggestion.service.ts

getSuggestions(term){
 return this.http.get('some-url')
      .map((res: Response) => res.json());
}

这使得网络请求 2 次。但是如果我稍微更改组件中的代码并手动订阅而不是使用异步管道,则网络请求只会发出一次。

component.ts

this.term.valueChanges
  .filter(term => term && term.length)
  .switchMap(term => this._suggestionsService.getSuggestions(term, uuid))
  .subscribe(value => this.suggestions = value);

component.html

<ul [hidden]='!suggestions.length'>
<li *ngFor='let suggestion of suggestions'>{{suggestion.name}}</li>
</ul>

两者的结果都很好。我只关心网络请求的数量。我想我缺少一些关于可观察对象的概念。

【问题讨论】:

  • 您的模板中是否碰巧有 2 个| async
  • @HarryNinh 是的,我已经更新了问题中的模板。

标签: javascript angular rxjs


【解决方案1】:

问题是模板中有 2 个async 导致 observable 被多次订阅,因此请求被发出 2 次。

使用share 可以解决问题:

this.suggestions = this.term.valueChanges
    .filter(term => term && term.length)
    .switchMap(term => this._suggestionsService.getSuggestions(term, uuid))
    .share();

【讨论】:

  • 这就是我的情况。我的模板中碰巧有三个async 管道,因此每个管道有三个请求。使用来自rxjsshare() 运算符做到了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
  • 2019-06-22
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 2016-06-23
相关资源
最近更新 更多