当我尝试从html调用getHistoryData()时,出现错误“ ERROR TypeError:无法设置未定义的属性'id'”。
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)
}
当我如注释代码所示直接分配有效负载对象的值时起作用,但是当我尝试通过函数分配数据时会抛出错误。
答案 0 :(得分:2)
因为当您执行payload: Data =
时,您正在分配完整的对象。在函数中,您已经期望payload
属性与对象值一起存在,但是由于您仅命名了该属性,因此该属性是不确定的。确保为您的属性定义一个初始值,例如payload : Data = {};
,然后分配将按预期工作。
答案 1 :(得分:1)
仅在定义类型时,需要将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
}
答案 2 :(得分:1)
您需要先用对象初始化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
}