Angular Error: Trying to access a property on an undefined variable

I'm currently having an issue with assigning data from an API to my Angular component file. Whenever I try to assign the data to my object variable, I receive an error stating: "cannot set property of undefined." Below is the relevant code snippet:

Class : UserDetails as

export class UserDetails {
    DOB?: string;
    Gender?: string;
    CellPhone?: string;
}

Component.ts :

export class PerComponent implements OnInit {

  public userProfileData: UserDetails;
  constructor( private commonService : CommonService) { 
    
    
  }
  ngOnInit(): void {
    this.loadData();
  }

  loadData() {
    let profileDetailParam = {ProcedureName: 'myprocname', Parameters: ['myparam']};
    this.commonService.GetDataFromStoredProcedure(profileDetailParam)
      .subscribe((data) => {
        let parseString = require('xml2js').parseString;
        let jsonData: UserDetails[];
        parseString(data, function (err, result) {
          if (result.NewDataSet != null)
            jsonData = result.NewDataSet.SPGetDetails[0];
          this.userProfileData = jsonData  ;
          console.log(this.userProfileData);
        });
      });
  }
}

The jsondata variable contains the expected data in JSON format.

Upon execution, I encounter the following error: core.js:4197 ERROR TypeError: Cannot set property 'userProfileData' of undefined

Although I understand that I need to initialize the userProfileDetails variable, I have tried doing so in both the constructor and ngOnInit methods without success.

Answer №1

The modification of the reference for "this" object has been made within a function

parseString(data, function (err, result) {

To access the "this" object from the outer scope, you can utilize an arrow function:

parseString(data, (err, result) => {
          if (result.NewDataSet != null)
            jsonData = result.NewDataSet.SPGetDetails[0];
          outerContext.userProfileData = jsonData  ;//////// use here
          console.log(outerContext.userProfileData);
        });

Further information can be found at: Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

Answer №2

The function "parseString" exists independently of "this", causing confusion when trying to assign values within a specific context.

To resolve this issue, create parseString as a standalone function within the component and invoke it using "this.parseString".

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

Javascript/Typescript Performance Evaluation

I am looking to create a visual report in the form of a table that displays the count of each rating based on the date. The ratings are based on a scale of 1 to 5. Below is the object containing the data: [ { "Date": "01/11/2022", ...

How come accessing the superclass's property with a getter in TypeScript is not working as expected?

class A { protected _value:number; get value() { return this._value; } } class B extends A { set value(v:number) { this._value = v; } } var b = new B(); b.value = 2; console.log(b.value);//undefined Coding Pla ...

Angular 2 - Implementing click event functionality to add an item

I've searched for a solution to this before, but the best answer I could find was from 9 months ago: here and it doesn't work with the latest Angular version. Is there a way to add a new item (<li> or any other) to my HTML with a simple cl ...

The Angular component fails to display the rendered HTML and instead displays the route for the HTML

I just finished creating a new Angular component, but when I try to view the rendered HTML, all I see is the route to the HTML file instead of the actual content. Here is my folder structure: This is the component I created, named server.component.ts: i ...

How can I dynamically update content using <router-outlet> on a secondary page?

When accessing my homepage, I want to see a header, footer, and the home-news-page displayed. Additionally, when I click on a link in the header, I would like the content of the home-news-page to change accordingly. Here is how my routing is currently set ...

The upcoming developer manages to execute the program successfully, however, it continues to load indefinitely

Executing the command yarn dev consistently runs successfully in my VS Code terminal: $ yarn dev yarn run v1.22.19 warning ..\..\..\..\package.json: No license field $ next dev ready - started server on 0.0.0.0:3000, url: http://localho ...

Retrieving the initial row of a specified category using ngFor in Angular 2

My challenge involves working with data in Angular 2. Here is a sample dataset: [ {text: "first", name: "a"}, {text: "rw", name: "a"}, {text: "ds", name: "b"}, {text: "asdf", name: " ...

Unexpected behavior with Angular 10 behavior subject - encountering null value after invoking .next(value) function

Can anyone help me solve the mystery of why my user value turns null after I log in? This is the login page where an API is called and the result is obtained as shown below: https://i.stack.imgur.com/kDjSy.png Here is the authentication service implemen ...

the undefined 'pipe' cannot be read

Trying to perform unit testing for an Angular component is a new experience for me. Currently, I am encountering a specific issue that I would like assistance with. The component in question contains the following select statement: this.store.select(getI ...

Is it necessary to unsubscribe from multiple switchmaps?

Consider the following scenario: Should I implement an unsubscribe in each instance of switchMap? And is it necessary to include a takeUntil after every switchMap operation? this.sharedSrv.postDetail.pipe( switchMap(post => { if (post) { th ...

Tips for invoking a function on a react-bootstrap-table component using TypeScript

One issue I'm encountering is trying to cast the "any" bootstrapTableRef to react-bootstrap-table, setting up the ref correctly, or importing it incorrectly. I am struggling to access the method of the imported table. While I found a solution using th ...

Executing a component method from a service class in Angular

When trying to call a component method from a service class, an error is encountered: 'ERROR TypeError: Cannot read property 'test' of undefined'. Although similar issues have been researched, the explanations mostly focus on component- ...

What are the steps to launch a Firebase application without requiring user authentication?

I have a unique firebase app/game that does not require authentication. My main goal is to allow anyone to easily access the website or mobile app and start playing right away, without the need for user IDs. I have been receiving numerous emails from Fireb ...

Using Angular 5 to access a variable within a component while iterating through a loop

I am currently in the process of transferring code from an AngularJS component to an Angular 5 component. Within my code, I have stored an array of objects in a variable called productlist. In my previous controller, I initialized another empty array nam ...

When I specify the type for the function parameter, an error occurs when I attempt to execute the function

When I assign a generic type to the function parameter and try to call the function, an error message pops up stating "This expression is not callable. Type unknown has no call signature." function a() { return 'abc' } function fun<T>(x: T ...

Error 404: Webpack Dev Server Proxy Not Found

Recently, I joined a new team where I am tasked with getting familiar with the project code as a freshman. The project is built using Angular2 and Spring Boot, along with Webpack for bundling assets and proxy settings through Webpack Dev Server to connect ...

Incorporating an offset with the I18nPluralPipe

Having trouble with my multiselect dropdown and the text pluralization. I attempted to use the I18nPluralPipe, but can't seem to set an offset of 1. ListItem = [Lion, Tiger, Cat, Fox] Select 1 Item(Tiger) = "Tiger", Select 3 Item(Tiger, Cat, Fox) = ...

What is the process for transferring a Pulumi Output<T> to the container definition of a task in ECS?

When creating a generic ECS service that deals with dynamic data, it is important to note that the containerDefinition within a Task Definition must be provided as a single valid JSON document. The code snippet for this setup looks like: genericClientServi ...

What could be causing the Angular HTTPClient to make duplicate REST calls in this scenario?

I am encountering an issue with my Angular service that consumes a Rest API. Upon inspecting the network and the backend, I noticed that the API is being called twice every time: Here is a snippet of my Service code: getAllUsers():Observable<any>{ ...

Can you provide guidance on how to communicate an event between a service and a component in Angular 2?

I'm currently working with angular2-modal to create a modal alert in my application. I am specifically trying to capture the confirm event that occurs when the modal is triggered. Does anyone know how I can achieve this? ...