I would like to have the http get results sorted in Angular 7.
A solution provided on the site used map to in combination with converting the response object to the destination type and getting back the json, but it seems to apply to an older version of Angular while I am using Angular 7.
public getAlertKeys (): Observable<AlertMsg[]> {
return this.http.get<AlertMsg[]>(this.alertsUrl);
}
Simply use the RxJS map operator and the sort function which is available on JavaScript arrays. Bear in mind that the function provided to sort needs to return a number (negative, zero or positive) to indicate the correct order.
Given you have the following AlertMessage model:
export class AlertMessage {
text: string;
priority: number;
}
When you want to sort by priority which is of type number, then you can use the following
return this.http.get<AlertMessage[]>(this.alertsUrl).pipe(
map(messages => messages.sort((a1: AlertMessage, a2: AlertMessage) => a1.priority - a2.priority ))
);
When you want to sort by text which is of type string, then you can use the following
return this.http.get<AlertMessage[]>(this.alertsUrl).pipe(
map(messages => messages.sort((a1: AlertMessage, a2: AlertMessage) => {
if(a1.text < a2.text) return -1;
if(a1.text > a2.text) return 1;
return 0;
}))
);
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