Angular 6 - 发布XML文件的httpClient

时间:2018-05-07 12:39:05

标签: angular typescript angular6

我正在使用Angular 6 httpClient并在服务中使用此代码:

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

}

我的问题是:我想发布一个xml文件,那么如何修改此代码呢?

1 个答案:

答案 0 :(得分:4)

您想要 POST XML数据吗?你需要一个内容类型' Http标题。

如果您还想接收XML,则响应类型的选项是json,text,blob和arraybuffer。 XML不是一个选项,所以你要求它作为纯文本但是(取决于你的API服务器)你想要设置接受类型' application / xml'和你的回复 - 输入'文字'。

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