5

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.

3
  • what are you getting in response? Commented Jun 23, 2017 at 11:59
  • @DeanChalk, can you post some codes andd what have you tried so far? Commented Jun 23, 2017 at 12:02
  • See if the answer to this question helps: stackoverflow.com/questions/41224749/… Commented Jun 23, 2017 at 12:04

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Did you happen to write a unit test for the sort method inside your request? I would be interested in seeing it if you still have the code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.