【发布时间】: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