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

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

*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; }); }); }) }

Jason
Guest

You have to sort array after each push, since responses come in random order:

this.arraytorender.push(objectinarray);
this.arraytorender.sort((a,b)=>{
  if (a.city < b.city)
    return -1;
  else if (a.city > b.city)
    return 1;
 else 
    return 0;
});

You might need to force change trigger:

this.arraytorender = this.arraytorender.concat();