KLTR
KLTR

Reputation: 1334

parse xml to json and subscribe with Angular4

I'm trying to convert an XML string to JSON by using xml2js, then i need to send and subscribe the result in another component.

getLastWeekSnow = function(){
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append("Authorization", "Basic " + btoa('user' + ":" + 'password')); 
headers.append('Content-Type' , 'application/x-www-form-urlencoded');    
return this.http.get(`${this.APIUrl}`, {headers:headers})
.map(res => {
  xml2js.parseString( res.text(), function (err, result) {
   console.dir(result); //Prints JSON object!
 });
})
 .subscribe(data => { 
 console.log(data); //Undefined !          
 });
}

so the console.dir(reults) gives me back what i need but in the subscribe (console.log(data)) i get undefined.

Why am i getting undefined in the subscribe , but gets the right Object in the .map ?

Upvotes: 0

Views: 1780

Answers (1)

Stephen
Stephen

Reputation: 1099

Make sure to return your data, otherwise it cannot subscribe

getLastWeekSnow = function(){
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append("Authorization", "Basic " + btoa('user' + ":" + 'password')); 
headers.append('Content-Type' , 'application/x-www-form-urlencoded');    

return this.http.get(`${this.APIUrl}`, {headers:headers})
.map(res => {
  let data;
  xml2js.parseString( res.text(), function (err, result) {
   console.dir(result); //Prints JSON object!
   data = result
 });
 return data;
})
 .subscribe(data => { 
 console.log(data); //Undefined !          
 });
}

Upvotes: 3

Related Questions