Retrieve XML from HTTPClient on Angular 5
Asked Answered
A

2

6

I'm trying to retrieve an xml from a SOAP API using the HttpClient from Angular

This is what's on my app.component.html:

<input type="submit" value="test POST" (click)="onClickMe()"/>

This is on my app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  results: string[];
  constructor(private http: HttpClient) {
    console.log('constructor opened');

  }
  ngOnInit(): void{
    console.log('onInit opened'); 

    }

  onClickMe(){
      var emp = '<<credentials to the webservice>>';
      var login = '<<credentials to the webservice>>';
      var pass = '<<credentials to the webservice>>';
      var id = "<<credentials to the webservice>>";

      const body = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\r\n  <soap12:Body>\r\n    <Lista xmlns=\"http://GSMMX.WebService/\">\r\n      <Emp>"+emp+"</Emp>\r\n      <Login>"+ login +"</Login>\r\n      <Senha>"+ pass +"</Senha>\r\n      <id>"+ id +"</id>\r\n    </Lista>\r\n  </soap12:Body>\r\n</soap12:Envelope>";
      const url = "<<webserviceURL>>";
      console.log('onClickme opened');

      this.http.post(url, body, {
        headers: new HttpHeaders()
        .set('Content-Type', 'text/xml') 
        .append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS') 
        .append('Access-Control-Allow-Origin', '*')
        .append('Access-Control-Allow-Headers', "Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Request-Method")
  }).subscribe(data => {
        console.log(data);

      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.log('An error occurred:', err.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
      }
    );

  }


}

So, I did the same request using Postman and copied the url and body exactly as the succeeded POST worked. I tried to do that using Angular 5 and it's not working, it's returning the following message:

Backend returned code 200, body was: [object Object]

Does someone know how do I make this work? The request is getting a 200 code but the response is not coming the right way.

I appreciate any help!

Abettor answered 7/11, 2017 at 13:49 Comment(0)
D
5

If you want to get the response as text. You can try adding { responseType: 'text' }.

{
        headers: new HttpHeaders()
        .set('Content-Type', 'text/xml') 
        .append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS') 
        .append('Access-Control-Allow-Origin', '*')
        .append('Access-Control-Allow-Headers', "Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Request-Method")
  , responseType:'text'}
Dwinnell answered 7/11, 2017 at 14:44 Comment(5)
Do you know how I retrieve a specific value within the response?Abettor
If the response is XML as you said then you have to use a library to parse the xml to json. Unfortunately I didn't use any myself so I don't have a recommendation. You can try to use a regular expression if the response is small and you only need one value, but it is highly unrecommended.Dwinnell
i have converted it to json, but even with json I don't know how to use it. Do you know? I'm posting a new question with it.Abettor
@Abettor The response's body will be a string that you can do as you pleaseSchaller
I don't know why everybody is talking about JSON. Once you set responseType: "text", which is correct, you need to take the result you get -- a string, containing the raw XML -- and make a DOMParser, then call parseFromString, which will give you an XMLDocument. There's no reason to convert to JSON.Hydroxy
M
5

If { responseType: 'text' } didn't do the trick, try { responseType: 'text' as 'text' }.

To convert the XML response to JSON, I used the script from this website XMLParser based on Lodash.

Another solution you can use is xml2js.

Misogynist answered 10/1, 2018 at 23:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.