Paintbox
Paintbox

Reputation: 407

Angular : Can't order array by ascending order

First of all sorry for my bad English. My website consume an asp.net core Api. The method to recover datas is the following:

getData(): Observable<INavigation> {
let apiNavigation: string = environment.apiAddress + 'Navigation';
this.repository.getData(apiNavigation)
    .subscribe((response) => {this.navigations = response as INavigation[]});
return this.navigations.sort((a,b) => b.sequence - a.sequence) as INavigation[];

}

This method use a repository service who uses HttpClient get method. I have result in the response and finally I try to order results by ascending order on sequence field but it doesn't. Is there anyone who can help me? Thanks

Upvotes: 0

Views: 168

Answers (1)

lbsn
lbsn

Reputation: 2412

Couple of issues with your code.

First of all, you need to sort the array within the subscribe callback, otherwise you end up sorting the array before it is set (the callback is async):

getData() {
    let apiNavigation: string = environment.apiAddress + 'Navigation';
    this.repository.getData(apiNavigation).subscribe(response => {
      this.navigations = response as INavigation[];
      this.navigations.sort(
         (a, b) => b.sequence - a.sequence
      )
    });
  }

Moreover, you declare getData return type as Observable, but you're trying to return a plain array instead. Since you're storing the sorted array as an instance member I guess getData might be void.

Upvotes: 1

Related Questions