Alia Sana
Alia Sana

Reputation: 39

fetching xml from web service in Angular 4

I am simply trying to retrieve xml data from some domain and read them onto my application. For now, I just want to read raw data. From my research, It comes to me that it is best to convert xml into json and load them onto the application. Here is what I tried to convert and print them. Could anyone advice on what I am doing wrong?

getProduction() {   
var headers = new Headers({ 'Content-Type': 'text/xml'})
headers.set('Accept', 'text/xml'); 
headers.set('Content-Type', 'text/xml');

//make the http request 
return this.http.get(this.url, {headers: headers})
                .map(res => JSON.parse(parseString(res.text(),'')))
                //Print JSON data?
                .subscribe(data =>{console.log(data);});
}

private handleErorr( error: Response){
  console.log('something went wrong');
  return Observable.throw(error.json().error || 'server error');
}

Upvotes: 2

Views: 5071

Answers (1)

Martin Adámek
Martin Adámek

Reputation: 18399

There are 2 problems with your code:

  1. parseString() method is not synchronous, so it will not return the parsed object, you need to use callback for this.

  2. You are trying to convert the result of parseString() to JSON via JSON.parse(). That is just wrong, as the result should be already JS object. You do not need the JSON.parse() call at all.

Try it like this:

getProduction() {
    var headers = new Headers({'Content-Type': 'text/xml'})
    headers.set('Accept', 'text/xml');
    headers.set('Content-Type', 'text/xml');

    //make the http request
    return this.http
        .get(this.url, {headers})
        .subscribe(res => {
            parseString(res.text(), (err, result) => {
                if (err) {
                    return console.log('invalid XML');
                }

                console.log(result);
            })
        }, err => this.handleError(err);
}

private handleErorr(error: Response) {
    console.log('something went wrong');
    return Observable.throw(error.json().error || 'server error');
}

Upvotes: 1

Related Questions