A mistake has occurred: Unhandled promise rejection TypeError: Unable to assign the property 'devices' to an undefined object in Ionic 4 with Angular

Within my MyDevicesPage class, I am attempting to manipulate the res object and then pass it to the updateDevicesToServer method of DataService for further actions. The code compiles without errors, but at runtime, an error is thrown: ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'devices' of undefined

Below 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>  
}

Upon Console Logging res, the following output is shown:

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

Answer №1

This error is occurring because you need to define the data object before attempting to set data.devices = res;. Consider making the following adjustment:

const updatedData: UpdatedResDevices = {
    devices: res,
    token: this.authenticationService.getAccessToken(),
};
this.devicesList = res.devices;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Body Parser is having trouble reading information from the form

I'm struggling to understand where I'm going wrong in this situation. My issue revolves around rendering a form using a GET request and attempting to then parse the data into a POST request to display it as JSON. app.get('/search', (re ...

jQuery allows us to set two separate conditions for two distinct variables

I've written this function: settings_rc_left.on('click', function(){ var settings_list_last_element_id_one = settings_menu_element.attr('id') == 'r_02', settings_list_last_element_id_two = settings_menu_eleme ...

Navigating through nested Firebase realtime DB queries using await/async techniques

In the process of developing a Firebase function (Gist), I encountered a challenge that I'm seeking assistance for. The function starts by querying a realtime database reference (events) using this code: await admin.database().ref('/events_geo ...

The try-catch statement in Typescript is generating an inconsistent return error

I've encountered an issue with a TypeScript function that is flagging inconsistent return error. The function includes a try block that returns a value and a catch block that throws an error, resulting in the inconsistency. I am struggling to find a w ...

When running the npm install command for Angular, an error occurred stating: "npm ERR! Maximum call stack

Upon running npm install, I encountered the following message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2256510f514b4f524e470f4351566213100c160c12">[email protected]</a>: NOTICE: ts-si ...

What is the best way to ensure webpacker compiled javascript only runs once the page has finished loading in a rails application

What is the best location to place window.onload for it to execute on every page within a Rails 6 application? ...

Displaying text that follows the cursor on a JavaScript mouseover event

When I hover over the pin with my cursor, the text should move along with the mouse. However, the current position of the text is off and needs to be adjusted to be next to the pin. What is a more accurate way to calculate the correct position? var toolt ...

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

Guide on how to navigate back to the login page when the access_token in local storage is not defined

Whenever my localStorage turns undefined, I need to redirect the user to the login page. However, this is not working as expected and I'm not sure what the issue is. Below is the code from my PrivateRoute.js: PrivateRoute.js import React from " ...

Troubleshooting Angular 4's ng-selected functionality

I'm currently facing an issue with getting ng-selected to function properly. Initially, I attempted to simply add selected in the option tag, but later discovered that I should be using ng-select. Despite trying variations such as ng-selected="true" a ...

Exploring the power of utilizing multiple classes with conditions in Angular 2+

Can you help me figure out how to use a condition for selecting multiple classes with [ngClass] in Angular? <td> <span [ngClass]="{ 'badge badge-success': server.type === 'PRODUCTION', 'ba ...

Guide on transferring data from a component to App.vue in Vue 3, even with a router-view in the mix

I have the following layout: src components Footer.vue views Page.vue App.vue I want to access the 'message' vari ...

The Add and Update functions of an AngularJS application are malfunctioning in Internet Explorer

Encountered a situation where updates and additions in IE show results in Chrome :D // Extract category object and id from the parent $scope.addNewCategory = function (category, parentId) { $scope.resetError(); category.parentId = par ...

Blog entries alternating between a pair of distinct hues

I want to create a design where each post container has a different color from the one next to it. Essentially, I would like the containers to alternate between two distinct colors. The left side shows how it currently appears, while the right side depict ...

Utilize jQuery script on every single element

Is there a way to implement a jquery function on elements that are dynamically loaded via ajax? <span class="h">Test</span><br /><br /> <span class="h">Test</span><br /><br /> <span class="h">Test</ ...

A fresh javascript HTML element does not adhere to the css guidelines

While attempting to dynamically add rows to a table using Javascript and jQuery, I encountered an issue. Here is my code: <script> $(document).ready(function(){ for (i=0; i<myvar.length; i++){ $("#items").after('<tr class="item- ...

Incorporating Recoil with React, a substantial array is experiencing lags due to numerous re-renders

I currently have an array of around 400 objects within my application. The hierarchy of components in my tree is structured as follows: App -> Page (using useRecoilState(ListAtom) for consumption) -> List -> Item (utilizing useSetRec ...

Tips for managing a 64-bit signed integer received from a NextJS backend API

I am currently developing a NextJS application in which one of the backend API routes sends back a JSON object that includes a 64-bit signed integer. // userID represents the 64-bit signed integer res.status(200).json({ id: userId, attributes: userAttribut ...

The ExpressJS middleware is executing twice

I'm experiencing an issue with the following code snippet. When I include the middleware logger() as the first argument to app.use(), it is called twice. However, when I place it as the second argument, it doesn't get executed at all. Can anyone ...

Executing two Ajax calls in ReactJS with different parameters can improve the efficiency of your

Why does the second Ajax call overwrite the first one, causing the results to be different each time I refresh it? In the first Ajax call, I have set tests: [], testsHistories: [] in the setState function. However, the second Ajax call only sets the stat ...