简体   繁体   English

Angular 2和RxJS-从2个来源进行排序

[英]Angular 2 & RxJS - Sort from 2 sources

I have a list of objects returned from the server via an Observable. 我有一个通过Observable从服务器返回的对象的列表。 That list is displayed in the template with ngFor. 该列表与ngFor一起显示在模板中。 I also have a dropdown to sort the list. 我还有一个下拉列表来对列表进行排序。

I have the sort working properly when the server returns the list but now I am trying to also sort the list when the comboBox is selected. 服务器返回列表时,排序工作正常,但是现在,当选择comboBox时,我也尝试对列表进行排序。

How can I sort the stream from the dropdown and the source and not have to use local variable to store the data? 如何从下拉列表和源中对流进行排序,而不必使用局部变量来存储数据?

Sample Code: 样例代码:

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));

Template: 模板:

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

You can use combineLatest : 您可以使用combineLatest

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

Don't forget to import it: 不要忘记导入它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM