*ngFor的渲染顺序在HTTP / JSONP调用后不可靠?



我使用"键"数组中的信息进行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>

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

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

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

最新更新