Search code examples
httpangularjsonpngfor

*ngFor's rendered order is unreliable after an HTTP/JSONP call?


I make a JSONP call using information from an array of "keys", which are in a particular order. I want the resulting new array, to be the same order as the source array of keys. This happens sometimes, but not always.

I have tried forEach, for loop, a simple array with just the key values, and an array with the field "name" followed by the key value. No idea why I can't get a consistent order. Following is with a simple array and just key values.

 /*separate defining class*/
 export class ArrayObjectItem {
  city: string;

constructor(city: string) {

this.city = city;
 }

  }
  /**/

  /*Below follows the code inside the main bootstrapped/rendering component*/

 names: [] = ['name1', 'name2', 'name3', 'name4', 'name5'];
 arraytorender: Array<ArrayObjectItem>[] = [];

this.names.forEach(name => {
  this.aJSONPservice.getData(name).subscribe(response => {
    const objectinarray = new ArrayObjectItem("null");
    objectinarray.city = response.city;
 this.arraytorender.push(objectinarray);

 });
 });

In the view of the main component:

<div *ngFor="#item of arraytorender">
 {{item.city}}
</div>

Solution

  • *ngFor does the right thing. The array is just not sorted.
    If you sort it you get the desired result:

      ngOnInit():any {
        this.names.forEach(name => {
          this._cityService.getCity().subscribe(response => {
            const objectinarray = new ArrayObjectItem("null", "null");
            objectinarray.city = response.city;
            objectinarray.namefromkeys = name;
            this.arraytorender.push(objectinarray);
            this.arraytorender.sort((a,b) => {
              if(a.namefromkeys == b.namefromkeys) {
                return 0;
              }
              if(a.namefromkeys > b.namefromkeys) {
                return 1;
              }
              return -1;
            });
          });
        })
      }