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.
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.
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