2

我正在使用 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 文件,那么如何修改此代码来做到这一点?

4

1 回答 1

4

您想发布XML 数据吗?您需要一个“Content-Type”Http 标头。

如果您还想接收 XML,则响应类型的选项是 json、text、blob 和 arraybuffer。XML 不是一个选项,因此您将其作为纯文本请求,但(取决于您的 API 服务器)您希望将 Accepts 类型设置为“application/xml”,并将您的 Response-Type 设置为“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));
  }
于 2018-05-07T14:12:33.983 回答