2016-08-03 109 views
3

我正在使用Angular 2 RC-4。我試圖在輸入框發生變化時發出網絡請求。但是這個請求被調用了兩次。switchMap:多個(2)請求被觸發

我的代碼如下所示:

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

難道你碰巧有2'|異步'在你的模板? –

+0

@HarryNinh是的,我已經更新了問題中的模板。 – ritz078

回答

3

問題是在模板中有2 async,導致observable被多次訂閱,因此請求被做了2次。

使用share將這樣的伎倆:

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