Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list that is held as an Observable (RxJS, Angular 2)

I am new to both Angular2 and RxJS.

I have set up a http service that essentially return to me an 'Observable'.

I am saving the Observable in a variable called items items : Observable.

My template (right now) just displays the contents

<ul>
    <li *ngFor="#item in items | async>{{item.name}} | {{item.group}}</li>
</ul>

This much works well.

I am now in the position where I want to sort my items - by name or group based on a click handler. However, I see no way to sort the array that is held within the Observable.

Any help is appreciated.

Thanks.

like image 541
Gratus D. Avatar asked Dec 05 '25 10:12

Gratus D.


1 Answers

I'm going to assume you have another observable that represents the current property you want to sort on:

const sortProperty$ = /* an observable of string values */

You can perform a combineLatest on this stream and the items$ stream (so we get the latest sort and list values). We can then use this information to create a new stream that will emit our sorted lists:

const sortedItems$ = Rx.Observable.combineLatest(sortProperty$, items$, (prop, items) => {
    return _.orderBy(items, prop);
});
like image 114
Calvin Belden Avatar answered Dec 08 '25 02:12

Calvin Belden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!