Angular 6-httpClient发布XML文件
我正在使用Angular 6 httpClient,并在服务中包含以下代码:Angular 6-httpClient发布XML文件,angular,typescript,angular6,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({ p
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文件,那么如何修改此代码来实现这一点呢?您想发布xml数据吗?您需要一个“内容类型”Http头
如果还希望接收XML,则响应类型的选项有json、text、blob和arraybuffer。XML不是一个选项,因此您要求将其作为纯文本,但(取决于您的API服务器)希望将接受类型“application/XML”和响应类型设置为“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));
}
post(){
//设置HttpHeader以请求XML。
常量httpOptions={
标题:新的HttpHeaders({
“Content-Type”:“application/xml”,//只需将postedData
更改为您的xml字符串添加“Content-Type”标题和可选的“accept”const-headers=new-HttpHeaders();headers=headers.append('Content-Type':'text/xml');headers=headers.append('accept','text/xml'))
然后将有效负载作为字符串发送。它的响应类型为:“text”作为“json”,并且应该超出1级,在标题之后:{…}。请参阅