I just want to sort data on an observable of my class type 'Category'. So Observable < Category[] > I want to sort.
So I upgraded to Angular6 and rxjs6 with it. One issue that is probably simple Typescript that I do know is how do I just do a 'sort' operation like:
sort((x,y) => x.description < y.description ? -1 : 1)
Inside of the new Angular6? I used to do this in 5
var response = this.http.get<Category[]>(this.endpoint);
.map((result: Response) => this.alphabetize(result));
alphabetize = (result: Response) => this.Categories = result.json()
.sort((x,y) => x.description < y.description ? -1 : 1)
And it worked fine. Now in the HttpCLIENTModule and HttpClient that Angular wants you to use it is simpler:
var data = this.http.get<Category[]>(this.endpoint);
I just put the magic <(object)> before my endpoint and it does it for me. Cool. But I am not seeing how you get inside the object easily to sort from it with Source, Pipe, from, of. I know it is probably something simple I just don't know the syntax for.
Description. The KnockoutJS Observable sort() method sorts all items in the array. By default, items are sorted in an ascending order. For sorting an array in a descending order, use reverse() method on sorted array.
Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example: The HTTP module uses observables to handle AJAX requests and responses. The Router and Forms modules use observables to listen for and respond to user-input events.
RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.
RxJS introduces Observables, a new Push system for JavaScript. An Observable is a Producer of multiple values, "pushing" them to Observers (Consumers). A Function is a lazily evaluated computation that synchronously returns a single value on invocation.
It is:
this.http.get<Category[]>(this.endpoint).pipe(
map(results => results.sort(...))
);
Or since sort
modifies existing array, it's more semantically correct to provide side effects in do
/tap
:
this.http.get<Category[]>(this.endpoint).pipe(
tap(results => {
results.sort()
})
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With