我的应用程序在角度2:
上有这个GET数据(http服务) private _url = "http://10.77.7.77/monitoring/api/v1/services/list";
constructor(private _http: Http) {
}
getServices(): Observable<any> {
return this._http.get(this._url)
.map(res => res.json());
}
一切都很好,但现在我的任务是使用另一个URL创建一个POST数据:
private _url2 = 'http://10.77.7.77/monitoring/api/v1/action/stop';
id - 这个json的服务数量:
[{
"nodename": "10.46.2.152",
"servicelist": [{
"id": "3827aa4b204fc2e122f452c1c1ceeaf15109364698d5d0f2153efa6e9487a968",
"name": "Nginx",
"status": "Online",
"servicecontrolled": true
}]
我写了这个POST数据:
postServices(post: { title: string, status: string, id: number }): Observable<any> {
let _url3 = `${this._url2}/${post.id}`
let headers = new Headers();
headers.append('Content-Type', 'application/json');
const body = JSON.stringify(post);
return this._http.post(_url3, body, post)
.map(res => res.json())
}
有这个事件
onPost(title: string, body: string, id: string) {
this._service.postServices({title: title, body: body, id: +id})
.subscribe(
response => this.response = response,
error => console.log(error)
);
}
这是我的模板:
<button *ngIf="!!service_rec.servicecontrolled"
[style.background-color]="service_rec.controlled
== 'true' ? 'green' : 'orange'"
class="btn btn-warning"
(click)="onPost()">
{{ service_rec.servicecontrolled | json | toOnOff }}
</button>
现在我有一些错误500 (Internal Server Error)
答案 0 :(得分:0)
如果您想发布JSON数据,只需使用以下内容:
// From RC2
postServices(post: { title: string, body: string, id: number }): Observable<any> {
return this._http.post(this._url2, post)
.map(res => res.json())
}
Angular2会自动为您设置application/json
内容类型并序列化您的帖子对象(JSON.stringify
)。
如果要根据自己的JSON内容进行序列化(在排除RC2之前),则需要明确添加内容类型:
postServices(post: { title: string, body: string, id: number }): Observable<any> {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this._http.post(this._url2, post, { headers })
.map(res => res.json());
}