user9273032
user9273032

Reputation:

Angular 6 - httpClient posting an XML file

I am using Angular 6 httpClient and have this code in a service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'text/xml' })
};

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  post() {
      const postedData = { userid: 1, title: 'title here', body: 'body text' };
      return this.http.post('this url here', postedData, httpOptions).subscribe(result => {
        console.log(result);
      }, error => console.log('There was an error: '));
  }

}

My question is: I want to post an xml file so how do I modify this code to do that?

Upvotes: 2

Views: 13098

Answers (1)

Rap
Rap

Reputation: 7292

You want to POST XML data? You need a 'Content-Type' Http header.

If you want to also receive XML, your options for a response type are json, text, blob, and arraybuffer. XML is not an option, so you ask for it as plain text but (depending on your API server) you want to set the Accepts type 'application/xml' and your Response-Type to 'text'.

post() {
  // Set your HttpHeaders to ask for XML.
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/xml', //<- To SEND XML
      'Accept':  'application/xml',       //<- To ask for XML
      'Response-Type': 'text'             //<- b/c Angular understands text
    })
  };
  const postedData = `
    <userid>1</userid>
    <title>title here</title>
    <body>body text</body>`;

  return this.http.post('this url here', postedData, httpOptions)
    .subscribe(
      result => { 
        console.log(result);  //<- XML response is in here *as plain text*
      }, 
      error => console.log('There was an error: ', error));
  }

Upvotes: 4

Related Questions