简体   繁体   中英

Angular2 HTTP POST using observables subscribe shows data as 'undefined'

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!

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);              
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM