Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting HTTP get data in Angular 7

Tags:

angular

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);
}
like image 835
syphon228 Avatar asked Feb 24 '26 16:02

syphon228


1 Answers

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;
    }))
);
like image 175
baumgarb Avatar answered Feb 27 '26 06:02

baumgarb