如何修复“错误类型错误:无法设置未定义的属性‘id’”

cvg*_*cvg 6 html typescript angular

当我尝试从 html 调用 getHistoryData() 时,出现错误“错误类型错误:无法设置未定义的属性‘id’”。

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

Run Code Online (Sandbox Code Playgroud)



// 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)
  }
Run Code Online (Sandbox Code Playgroud)

当我直接分配有效负载对象的值时有效,如注释代码所示,但是当我尝试通过函数分配数据时,它会引发错误。

wen*_*jun 7

payload在为属性分配任何值之前,您需要使用对象初始化属性。

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
}
Run Code Online (Sandbox Code Playgroud)


dee*_*Dev 5

您需要实例this.payload化为一个对象(打字稿,一个正确形状的对象),因为您只是定义一个类型。只需尝试使用新语法来实例this.payload化为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
  }
Run Code Online (Sandbox Code Playgroud)