Angular 2 & RxJS - Sort from 2 sources

203 Views Asked by At

I have a list of objects returned from the server via an Observable. That list is displayed in the template with 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.

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$'>
1

There are 1 best solutions below

0
On BEST ANSWER

You can use 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';