Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "ERROR TypeError: Cannot set property 'id' of undefined "

I get an error "ERROR TypeError: Cannot set property 'id' of undefined" when i try to call getHistoryData() from html.

export class Data { 
    id : string ;
    fromTime : any ;
    toTime : any ;
    deviceType : string ;
    interval : any;
    params : string;
}




// payload : Data = {
  //   id : "00:12:4b:00:19:7b:27:7",
  //   fromTime: "1554422400000",
  //   toTime: "1554508799000" ,
  //   deviceType: "xxx",
  //   interval: "1199999",
  //   params: "temperature"
  // }

  payload : Data;

  response : any;


  generatePayload(){
    this.payload.id = "00:12:4b:00:19:7b:27:7",
    this.payload.fromTime = "1554422400000",
    this.payload.toTime = "1554508799000",
    this.payload.deviceType = 'xxx' , 
    this.payload.interval = 1000 ,
    this.payload.params = this.selectedParameter
  }

  getHistoryData(){
    this.generatePayload()
     this.historyDataService.getHistoryData(this.payload)
           .subscribe((data) => this.response = data)
  }

works when i assign the values of payload object directly as shown in the commented code, but when i try to assign the data through a function it throws an error.

like image 206
cvg Avatar asked Apr 12 '19 07:04

cvg


3 Answers

You need to initialise your payload property with an object before you assign it with any values.

payload : Data = {
  id : undefined,
  fromTime: undefined,
  toTime: undefined ,
  deviceType: undefined,
  interval: undefined,
  params: undefined
};

generatePayload(){
  this.payload.id = "00:12:4b:00:19:7b:27:7",
  this.payload.fromTime = "1554422400000",
  this.payload.toTime = "1554508799000",
  this.payload.deviceType = 'xxx' , 
  this.payload.interval = 1000 ,
  this.payload.params = this.selectedParameter
}
like image 79
wentjun Avatar answered Oct 19 '22 20:10

wentjun


You need to instantiate this.payload as an object (being typescript, an object of the correct shape) as you are only defining a type. Simply try using the new syntax to instantiate this.payload as Data.

 public payload: Data;

  generatePayload()
  {
    this.payload = new Data(); // will define an object with correct keys.

    this.payload.id = "00:12:4b:00:19:7b:27:7",
    this.payload.fromTime = "1554422400000",
    this.payload.toTime = "1554508799000",
    this.payload.deviceType = 'xxx' , 
    this.payload.interval = 1000 ,
    this.payload.params = this.selectedParameter
  }
like image 25
Dince12 Avatar answered Oct 19 '22 20:10

Dince12


Because when you do payload: Data = you are assigning the full object. In the function you already expect the payload property to exist with an object value but since you have only named the property it will be undefined. Be sure to define an initial value for your property, eg payload : Data = {}; and then the assignment will work as expected.

like image 35
Liam Martens Avatar answered Oct 19 '22 18:10

Liam Martens