为什么我的数组未定义,但实际上应该有一个对象?

时间:2019-05-14 12:08:56

标签: arrays angular undefined push

我正在尝试对一个应包含项目中某些对象的数组进行编码,但我总是收到一个错误消息,名称为:“ this.allgmArray未定义”,但实际上并非如此:

  allgmArray: DialogBook[];
[...]
load(){

    for(var i = 0; i < this.service.allgmTempArray.length; i++) {
      if(this.service.allgmTempArray[i].type == this.service.tempGroup.get('type').value){
        var fullName = this.service.tempGroup.get('fullName').value;
        console.log(fullName) //works fine
        var type = this.service.allgmTempArray[i].type;
        console.log(type) //works fine
        var device = this.service.allgmTempArray[i].device;
        console.log(device) //works fine
        var date_from = this.service.tempGroup.get('date_from').value;
        console.log(date_from) //works fine
        var date_to = this.service.tempGroup.get('date_to').value;
        console.log(date_to) //works fine
        var date_from_og = this.service.tempGroup.get('date_from_og').value;
        console.log(date_from_og) //works fine
        var date_to_og = this.service.tempGroup.get('date_to_og').value;
        console.log(date_to_og) //works fine
        var obj = {
          fullName: fullName,
          type: type,
          device: device,
          date_from: date_from,
          date_to: date_to,
          date_from_og: date_from_og,
          date_to_og: date_to_og
        }
        console.log(obj) //<- Comes out the right obj
        this.allgmArray.push(obj) //<- I think heres the problem
      }
    }
    console.log(this.allgmArray) //Error: this.allgmArray is undefined
//And "DialogBook" interface look like:
export interface DialogBook {
    fullName: String;
    device: String;
    type: String;
    date_from: String;
    date_to: String;
    date_from_og: Date;
    date_to_og: Date;
}

所以我真的不知道问题出在哪里,需要帮助

1 个答案:

答案 0 :(得分:3)

allgmArray: DialogBook[];

是定义,不是实例。

allgmArray: DialogBook[] = [];

应解决您的问题。