0

我使用来自“键”数组的信息进行 JSONP 调用,这些“键”按特定顺序排列。我希望生成的新数组与键的源数组的顺序相同。这种情况有时会发生,但并非总是如此。

我试过forEach,for循环,一个只有键值的简单数组,以及一个字段“name”后跟键值的数组。不知道为什么我不能得到一致的订单。以下是一个简单的数组和键值。

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

 });
 });

从主要组件来看:

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

2 回答 2

1

*ngFor做正确的事。数组只是没有排序。
如果你对它进行排序,你会得到想要的结果:

  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;
        });
      });
    })
  }
于 2016-04-14T15:16:33.867 回答
0

您必须在每次推送后对数组进行排序,因为响应是随机顺序的:

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

您可能需要强制更改触发器:

this.arraytorender = this.arraytorender.concat();
于 2016-04-14T16:47:56.550 回答