2016-12-19 78 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';