0

This is the code I have written in angular/ionic

this.http.get('/assets/xml/app.xml').subscribe(data => {

  xml2js.parseString(data.text(), function(err, result) {
    console.log('result', result);
    this.posts = JSON.stringify(result);
    console.log('type of', this.posts);
  });
}, error => {
  console.log(JSON.stringify(error.json()));
});

This function throws following error when assigning the result to the post variable.

Cannot set property 'posts' of undefined

Sankar
  • 6,182
  • 2
  • 23
  • 43
Ved Prakash
  • 29
  • 1
  • 1
  • 4

2 Answers2

0

I think it because this refers to the promise itself, you could use the arrow function expression, which preserves the value of this.

Please use following code it will help you.

 this.http.get('/assets/xml/app.xml').subscribe(data => {

      xml2js.parseString(data.text(), (err, result) => {

          this.posts = JSON.stringify(result) || {};

       });

  }, error => {
      console.log(JSON.stringify(error.json()));
 }); 

Please check the same question here.

Hope this will help you !!

Santosh Shinde
  • 5,567
  • 5
  • 37
  • 58
0

I think it is because this is inside the wrong environment. Try getting the instance before accessing that function:

    var self = this;
    this.http.get('/assets/xml/app.xml').subscribe(data => {

        xml2js.parseString(data.text(), function (err, result) {
            console.log('result',result);
            self.posts = JSON.stringify(result);
           console.log('type of',this.posts);
        });
    }, error => {
        console.log(JSON.stringify(error.json()));
    });
eLRuLL
  • 17,114
  • 8
  • 67
  • 91