0

I'm POSTing data using Angular 2 to an URL which returns back XML response, I want to convert the data to JSON so I'm using xml2js.

The conversion happens fine, but I get 'data' as undefined in 'subscribe' block. Please correct me if I'm wring, I'm guessing since xml2js is an async operation, 'data' is undefined. So how do I handle this promise of promise situation and return the transformed JSON data correctly? Code below:

 this.http.post(this._yourUrl, formdata.toString(), options)
 .map(res => {
        xml2js.parseString( res.text(), function (err, result) {
        console.dir(result); // Prints JSON object!
        return result;
     });
 })
 .subscribe(data => { 
      console.log(data);              
 });

Any help is much appreciated. Thanks!

Malick
  • 477
  • 4
  • 16
  • try adding a return to `return xml2js.parseString...` or remove the braces from the map lambda method – CriPstian May 08 '17 at 09:24
  • CriPstian, I already tried adding a return to xml2js.parseString, it returns an SAXParser object. Removing the braces, causes compilation error. – Malick May 08 '17 at 09:34

1 Answers1

3

Assuming xml2js.parseString is a sync operation,

Try this:

this.http.post(this._yourUrl, formdata.toString(), options)
 .map(res => {
        var myRes;
        xml2js.parseString( res.text(), function (err, result) {
            console.dir(result); // Prints JSON object!
            myRes = result;
        });
        return myRes;
 })
 .subscribe(data => { 
      console.log(data);              
 });
eko
  • 39,722
  • 10
  • 72
  • 98
  • echonax, it worked! thank you :) If you don't mind can you please provide me a link pertaining to this so that i can understand how this worked. – Malick May 09 '17 at 05:50
  • 1
    @Malick returning a result inside a libraries callback might be tricky. I assume this lib uses something like a stream or an unbreakable loop like `forEach` in its native code, so it wasn't returning anything. Therefore, returning the value outside of the `parseString` should solve the issue. Check this for an idea: http://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function/34653650 – eko May 09 '17 at 05:53
  • Okay. Will check that. Thanks again! – Malick May 09 '17 at 05:55
  • Understood that, another doubt though, hope you don't mind. How is xml2js.parseString an sync operation? Isn't it an async opeartion? And won't the 'return myRes' statement run before the async call completes, in that case how does the 'return' call gets called again after the assginment, 'myRes = result'? – Malick May 09 '17 at 06:03
  • @Malick well if the above code works, it's a sync operation. Like `JSON.parse(obj)` – eko May 09 '17 at 06:05
  • @Malick check this discussion: https://github.com/Leonidas-from-XIV/node-xml2js/issues/159 – eko May 09 '17 at 06:07