Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you sort an Observable<Item[]> in Angular 6 with rxjs 6?

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.

like image 895
djangojazz Avatar asked May 10 '18 14:05

djangojazz


People also ask

How do you sort an Observable array?

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.

What are observables in Angular 6?

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.

What is RxJS Observable in Angular?

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.

How does RxJS Observable work?

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.


1 Answers

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()
  })
);
like image 153
Estus Flask Avatar answered Oct 25 '22 08:10

Estus Flask