我从端点接收到以下响应

{
  "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;
     }
  }
}

我有一个常量存储来检查我是否可以评估数据
一切都很好。
问题是我想填充我的变量stors这是一个存储模型数组,它具有这些属性、存储、名称等。
我试图通过最后一行来做,但是出了点问题,
得到:
Cannot set property '0' of undefined

有什么想法吗?

最佳答案

错误是说,在循环的第一次迭代中,由于未定义this.stors[0]的赋值是不可能的。stors属性尚未初始化。考虑:

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

08-03 16:41