2016-12-19 76 views
0

我有一個通過Observable從服務器返回的對象列表。該列表使用ngFor顯示在模板中。我也有一個下拉列表來排序。Angular 2&RxJS - 從2個源排序

當服務器返回列表,但現在我想要在選擇組合框時對列表進行排序時,我的排序工作正常。

如何從下拉列表中排序流和源,而不必使用本地變量來存儲數據?

示例代碼:

let sortButton$ = new Subject(); 
let sortProp = 'myProperty'; 

this.handleSortButton(sortProp) { 
    sortButton$.next(sortProp); 
} 

// how can I retain my Observable and sort the values from the server when 
// a) the values come back from server (works with below) 
// b) the sort dropdown sends a new property value via the subject 
this.test$ = Observable 
       .of(['one', 'two', 'three']) 
       .map((data) => _.sortBy(data,this.sortProp)); 

模板:

<div *ngFor='let item of test$'> 

回答

2

您可以使用combineLatest

this.test$ = Observable 
    .of(['one', 'two', 'three']) 
    .combineLatest(this.sortButton$.startWith(this.sortProp)) 
    .map(([data, sort]) => _.sortBy(data,sort)) 

不要忘了將其導入:

import 'rxjs/add/observable/combineLatest'; 
import 'rxjs/add/operator/startWith';