0

I am new in Ionic. I tried to set data from web service to my variable but it's return

"Cannot set property 'xxx' of undefined"

but I already init variable to any

This is my code

import {RedditsService} from '../../app/services/reddits.service'; 
import xmljson from 'xmljson'; 

@Component({ 
  selector: 'reddits', 
  templateUrl: 'reddits.html' 
}) 
export class RedditsPage { 
  xxx:any;
  constructor(public navCtrl: NavController, private redditsService:RedditsService) { 

  } 

  ngOnInit(){ 
 this.getPosts(); 
  } 

  getPosts(){ 


 this.redditsService.getPosts().subscribe(response => {xmljson.to_json(response._body, function(error, data){ 
   var jsonData = data.ArrayOfMdReqOnProcess.mdReqOnProcess; 
   this.xxx = jsonData; 
   console.log(jsonData[1]) 
  }); 
 }); 
  } 
}

It's ok when I set data to data type var, but I don't want that because I want to send parameter "xxx" to the HTML page

How to resolve this problem?

ucMedia
  • 4,105
  • 4
  • 38
  • 46
user3001046
  • 235
  • 1
  • 10
  • 28

1 Answers1

0

In your function which is passed into the xmljson.to_json function, this does not refer to the Component. You can change the function declaration with simple arrow function to preserve this parameter to refer to the Component context.

getPosts() { 

 this.redditsService.getPosts()
                    .subscribe(response => {
                           xmljson.to_json(response._body, (error, data) => { 
                              var jsonData = data.ArrayOfMdReqOnProcess.mdReqOnProcess; 
                              this.xxx = jsonData; 
                              console.log(jsonData[1]);
                           }); 
                     }); 
} 

Also you have said that

I already init variable to any

xxx:any expression does not initialize your variable, it just sets the type of the variable. Initializing means that a value is assigned to it.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112