0

i am pretty new to typescript/Angular2. Let me sum up real quick what I'm trying to do with my method. I have a hard-coded XML data where I parse it to JSON, after that, I assign each JSON to a FormComponent object which has the properties of id, field, label. After assigning my object I push them to a local array. Here comes where I am stuck at. I want to assign my local(demoArray) to my global instance(jsonArray) but I get an error doing it like below. I have tried calling another function to assign it but I cannot access my global instance with this. So I would really appreciate it if you guys can help me with it. Thanks in advance :)

This is the instance that I'm trying to access(the function and instance are in the same class

jsonArray:Array<FormComponents> = [];

Where I'm trying to access jsonArray

parseToJson(){
    
    let xml = '<forms><id>1</id><field>text</field><label>Name</label><id>2</id><field>radio</field><label>radio</label></forms>';   
    var parseString = require('xml2js').parseString;
    parseString(xml, function (err:any, result:any) {
      let counter = result.forms.field.length;
      let demoArray: Array<FormComponents> = [];
      for (let i = 0; i < counter; i++) {
         const myObj = new FormComponents();
         myObj.id = result.forms.id[i];
         myObj.field = result.forms.field[i];
         myObj.label = result.forms.label[i];
         demoArray.push(myObj);
      }
      
      //console.log(demoArray);
      this.jsonArray = demoArray; //where I'm getting my error

      
    });

    console.log(this.jsonArray);

  }
  
}

2
  • 1
    Please see minimal reproducible example. Commented Mar 31, 2021 at 14:34
  • thanks a lot i will look in to this Commented Mar 31, 2021 at 16:02

1 Answer 1

1

The problem is here: parseString(xml, function (err:any, result:any) {...}

Inside a function, this points to the function itself.
You may use (err:any, result:any) => {...} instead.

FYI: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, i don't know why exactly that is the solution but I will look at the link you have given. Thanks a bunch again :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.