javascript - 错误错误 : Uncaught (in promise): TypeError: Cannot set property 'devices' of undefined in ionic 4 Angular

标签 javascript angular typescript ionic-framework interface

我有一个名为 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/

相关文章:

javascript - 为什么我的类型在 React 和 TypeScript 中为 null?

javascript - 有人可以向我解释我遇到的错误吗?

typescript - 何时在 typescript Angular 2 中使用 @Optional() 和三元运算符?

typescript - 使用 observables 跟踪 typeahead 列表中的当前位置

typescript - "find all references"不起作用,除非相关文件打开

typescript - 如何在 typescript 元组中使用扩展运算符?

javascript - 如何动态循环到 UL 和 LI 元素中?

javascript - 更新 mongodb 集合中的字段,即使它不存在

javascript - 从服务器检索 JSON.parse() 字符串

testing - 在生产模式下隐藏 angular2 组件的最佳解决方案?