How to parse xml in Angular 2

后端 未结 3 838
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 12:13

I\'m using an API that uses XML instead of JSON. Any suggestions on how to convert the following XML to JSON or how to properly use the data in an ngFor directive?

A

3条回答
  •  感情败类
    2020-11-28 12:35

    This is if you are using doing a POST and getting back XML response: Use xml2js - https://www.npmjs.com/package/xml2js

    1. npm install xml2js -g
    2. import in service file as : import * as xml2js from 'xml2js';

    3. Code:

      let formdata = new URLSearchParams();
      formdata.set('username','username');
      formdata.set('pw','pw');
      
      let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded' });
      
      let options = new RequestOptions({ headers: headers, method: RequestMethod.Post});      
      
      postCaseFile () {
      
           this.http.post(this._apiUrl, formdata.toString(), options)
           //convert to JSON here
           .map(res => {
                      xml2js.parseString( res.text(), function (err, result) {
                      console.dir(result); // Prints JSON object!
                 });
            }).subscribe(data => {    
              console.log(data);              
            });
      }
      

提交回复
热议问题