从Json Angular 5推入数组

时间:2018-05-06 15:39:18

标签: arrays json angular typescript parsing

我从端点收到以下回复

{
  "data": [{
    "volume": 4.889999866485596,
    "name": "Carton03",
    "weight": 5.75,
    "storage": 3
  }, {
    "volume": 2.6500000953674316,
    "name": "Carton02",
    "weight": 4.5,
    "storage": 2
  }, {
    "volume": 1.4500000476837158,
    "name": "Carton01",
    "weight": 5,
    "storage": 1
  }],
  "response": "true",
  "type": "Storages"
}

下面我试图在我的组件上创建一个数组:

export class StorageComponent {
   private data: any;
   private stors: Storage [];

   constructor (private storageService: StorageService  ) {}

   storage () {
     this.data =  this.storageService.Storage(); 
     //storageService.Storage is an assistant service that parse the response 
     // and brings me back only the data-array of the response
     for (let i = 0; i < this.data.data.length; i++) {
      const storages = this.data.data[i];
      console.log(storages.storage);
      console.log(storages.name);
      console.log(storages.weight);
      console.log(storages.volume);
      this.stors[i] = storages;
     }   
  }
}

我有一个const存储器来检查我可以评估数据 一切都很好。

问题在于我想填充变量stors,它是一个存储模型数组,具有这些属性,存储,名称等。

我试图通过最后一行做到这一点,但有些事情是错的, 得到:

Cannot set property '0' of undefined

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

错误在于,在循环的第一次迭代期间,无法分配this.stors[0],因为它未定义。 stors属性尚未初始化。考虑:

constructor (private storageService: StorageService) {
    this.stors = [];
}

答案 1 :(得分:1)

在定义stors属性时,只需进行初始化,如下所示:

private stors: Storage[] = [];

您也可以初始化其他属性:

private data: any = null;

你可以在构造函数或ngOnInit中初始化它,但我认为这是一种更好的方法来直接在属性中初始化数组。

初始化类属性将避免此类行为。