djangojazz
djangojazz

Reputation: 13252

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.

Upvotes: 36

Views: 43480

Answers (2)

greenCode
greenCode

Reputation: 117

For angular12 when I try this solution it give me this error.

TypeError: Cannot read property ‘sort’ of undefined TypeError: Cannot read property ‘sort’ of undefined

To fix this error. I used pipe

import { Pipe, PipeTransform } from '@angular/core';


@Pipe({
  name: 'sortByDate'
})
export class SortByDatePipe implements PipeTransform {

  transform(value: any, ...args: any[]): any {
    value = [...value]; // fixed to second error

    return value.sort((a, b) => new Date(b.date1).getTime() - new Date(a.date1).getTime());

  }

}

At this time it gives this.

TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’ Error ?

I already explain that in code(above) but you can check here if it doesnt solve the error.

Here is the html code

<div *ngFor="let item of data$ | async | sortByDate">
//your code goes here
</div>

Upvotes: 0

Estus Flask
Estus Flask

Reputation: 222780

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

Upvotes: 56

Related Questions