Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting data from Angular http get api call

Tags:

angular

rxjs

This seems like it should be a really trivial thing, but I'm really struggling to work out a neat non-hacky solution to a simple problem.

my http.get(... Angular call to my service brings back an Observable - which is a stream of T items (after I have mapped with response.json())

The Observable is a property on my component. I have a <select> element in the component template with the <option> elements created via the *ngFor="let item of myObservable | async" code in my template.

This has created a nice select element with all values that I expect showing up nicely in the browser :)

Now someone has asked me to sort the options in the select statement alphabetically.

I dont want to create a sorting pipe, as the Angular team recommend not doing that, and it seems that Observables are by their nature un-sortable.

Ive tried to convert the Observable into a simple array of results - but that seems impossible too.

So how do I achieve this simple thing? my JSON service returns 20 or so JSON objects, and I cant seem to work out how to get them sorted by one of their properties.

Thanks for any help.

like image 350
Dean Chalk Avatar asked Jun 23 '17 11:06

Dean Chalk


1 Answers

OK, Ive solved it (if anyone is interested;

My original code from the service was like this:

  public getAllItems(): Rx.Observable<DataItem> {
    var returnVar = this.http.get("http://localhost:8090/api/rest/dataitem")
      .map(res => {
        return res.json()
      });
    return returnVar;

But then I changed the observable to an observable of type array, and sorted it in the map

public getAllItems(): Rx.Observable<DataItem[]> {
    var returnVar = this.http.get("http://localhost:8090/api/rest/dataitem")
      .map(res => {
          var ret = <DataItem[]>res.json();
          ret.sort((a,b) => a.name < b.name ? -1 : 1);
          return ret;
      } );

I didnt realise that you could cast the response object into either a single item or the entire array.

Thanks for everyone who tried to help.

like image 70
Dean Chalk Avatar answered Oct 13 '22 03:10

Dean Chalk