Rishabh Gusain
Rishabh Gusain

Reputation: 687

ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'devices' of undefined in ionic 4 Angular

I have a class called MyDevicesPage which controls a page i am trying to manipulate the res object and then pass it to updateDevicesToServer method of DataService for further actions. the code compiles fine but in run time it throws an error ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'devices' of undefined

here are the class and associated interfaces

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 gives this

{devices : [{ssid:"ssid", name :"name"}]}

Upvotes: 1

Views: 1547

Answers (1)

Simon K
Simon K

Reputation: 2857

You're receiving this error because you are not initialising your data object before trying to assign data.devices = res;. I suggest the following update:

let data: ResUpdateDevices = {
    devices: res,
    token: this.authenticationService.getToken(),
};
this.devices = res.devices;

Upvotes: 1

Related Questions