Eduard Arevshatyan Eduard Arevshatyan - 3 months ago 15
TypeScript Question

Http service POST

I have this GET data (http service) in my application on angular 2:

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());
}


And everything is OK, but now my task is create a POST data, with another URL:

private _url2 = 'http://10.77.7.77/monitoring/api/v1/action/stop';


id - number of service this json:

[{
"nodename": "10.46.2.152",
"servicelist": [{
"id": "3827aa4b204fc2e122f452c1c1ceeaf15109364698d5d0f2153efa6e9487a968",
"name": "Nginx",
"status": "Online",
"servicecontrolled": true
}]


I wrote this POST data:

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())
}


with this event

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)
);
}


and this my template:

<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>


And now i have some error
500 (Internal Server Error)

Answer

If you want to post JSON data, just use the following:

// From RC2
postServices(post: { title: string, body: string, id: number }): Observable<any> {
    return this._http.post(this._url2, post)
        .map(res => res.json())
}

Angular2 will set automatically for you the application/json content type and serialize your post object (JSON.stringify).

If you want to serialize by your own JSON content (before RC2 excluded), you need to add the content type explicitly:

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());
}
Comments