我正在使用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>
两者的结果都很好。我关注的只是网络请求的数量。我想有一些关于我失踪的可观察物的概念。
答案 0 :(得分:7)
问题是模板中有2 async
导致observable被多次订阅,因此请求被做了2次。
使用share
可以解决问题:
this.suggestions = this.term.valueChanges
.filter(term => term && term.length)
.switchMap(term => this._suggestionsService.getSuggestions(term, uuid))
.share();