0

I am taking data from API to my Angular component file but when I assigned the data to my object variable It gives me error of cannot set property of undefined. Here is my code :

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);
        });
      });
  }
}

jsondata contains my expected data in JSON format.

I am getting the error core.js:4197 ERROR TypeError: Cannot set property 'userProfileData' of undefined

I understand that i didn't initialise the userProfileDetails but how and where should be done.

I tried in constructor and ngOnInit but nothing works

DevError404
  • 129
  • 2
  • 14

2 Answers2

2

the referencce of "this" object has been changed inside function

parseString(data, function (err, result) {

to access "this" object of outer scope you can use 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);
        });

You can read more here: Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

Clashsoft
  • 11,553
  • 5
  • 40
  • 79
0

The function "parseString" is existing outside of "this", so when you are asking it to assign that value, it does not know what "this" is within that context.

Perhaps define parseString as it's own function within this component and call it with "this.parseString".

cklimowski
  • 589
  • 6
  • 21