I'm trying to POST some data using angular and I keep getting an empty object on the response when I inspect it with Postbin. I subscribe to this function elsewhere in my code so I'm sure the request is going through:
Everything works fine using Postman, but I can't see what is wrong with the code below:
postRequest(order): Observable<any> {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const data = {
"data": {
"ID": "1",
"Name": "John",
"Class": "Adventurer",
"Items": [
"641",
"642",
"643",
"513",
"512"
]
}
}
return this.http.post('https://requestb.in/wjoscywj', { body: JSON.stringify(data) }, { headers: headers })
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
I would tweak a few things:
to be on safe side.
You do want JSON.stringify. I normally do it without {body: } same for headers. so you have
With the map you can just do
Remember you have to subscribe to an Observable to start things going.
In your case I would tend to have the service with signature:
That way you still have type safety at the method level.
Then, in the calling function do the map and subscribe like so:
Subscribe consists of 3 parts: Success, Error, Finally.
Error & Finally are optional.
If only 1 statement curly braces {} are optional.