Cra*_*018 2 typescript angular 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: '));
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:我想发布一个xml文件,那么我该如何修改此代码呢?
你想POST 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));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5544 次 |
| 最近记录: |