我有一个名为 MyDevicesPage 的类,它控制我试图操作 res 对象的页面,然后将其传递给 DataService 的 updateDevicesToServer 方法以进行进一步操作。代码编译正常,但在运行时会抛出错误 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'devices' of undefined
这是类和关联的接口(interface)
export class MydevicesPage implements OnInit {
devices : Array<deviceInterface>
constructor(private deviceService : DeviceService,private route: ActivatedRoute,private router: Router, private authenticationService : AuthenticationService) { }
ngOnInit() {
this.deviceService.getDevices().then((res : devicesInterface) => {
if(res){
let data : ResUpdateDevices
data.devices = res;
this.devices = res.devices;
data.token = this.authenticationService.getToken();
this.deviceService.updateDevicesToServer(data).subscribe(res => {
console.log(res)
},err=>{
console.log(err)
});
}
})
}
goto_device(ssid : String, name : String){
this.router.navigate(['members','device',ssid,name])
}
}
ResUpdateInterface接口(interface)
export interface ResUpdateDevices{
devices : devicesInterface
token : string
}
DeviceInterface接口(interface)
export interface deviceInterface {
ssid : String,
name : String
}
DevicesInterface接口(interface)
export interface devicesInterface {
devices : Array<deviceInterface>
}
Console Logging res 给出了这个
{devices : [{ssid:"ssid", name :"name"}]}
最佳答案
您收到此错误是因为您在尝试分配 data.devices = res;
之前没有初始化您的 data
对象。我建议进行以下更新:
let data: ResUpdateDevices = {
devices: res,
token: this.authenticationService.getToken(),
};
this.devices = res.devices;
关于javascript - 错误错误 : Uncaught (in promise): TypeError: Cannot set property 'devices' of undefined in ionic 4 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54858837/