Angular 6 - httpClient 发布一个 XML 文件
Angular 6 - httpClient posting an XML file
我正在使用 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: '));
}
}
我的问题是:我想 post 一个 xml 文件,那么我该如何修改这段代码来做到这一点?
您要POSTXML数据?你需要一个 'Content-Type' Http header.
如果您还想接收 XML,您的响应类型选项有 json、文本、blob 和数组缓冲区。 XML 不是一个选项,所以你要求它作为纯文本但是(取决于你的 API 服务器)你想将接受类型 '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));
}
我正在使用 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: '));
}
}
我的问题是:我想 post 一个 xml 文件,那么我该如何修改这段代码来做到这一点?
您要POSTXML数据?你需要一个 'Content-Type' Http header.
如果您还想接收 XML,您的响应类型选项有 json、文本、blob 和数组缓冲区。 XML 不是一个选项,所以你要求它作为纯文本但是(取决于你的 API 服务器)你想将接受类型 '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));
}