I wrote the following code in Angular 2:
this.http.request(\'http://thecatapi.com/api/images/get?format=html&results_per_page=10\').
subscribe((re
Here is an example of a get
http call:
this.http
.get('http://thecatapi.com/api/images/get?format=html&results_per_page=10')
.map(this.extractData)
.catch(this.handleError);
private extractData(res: Response) {
let body = res.text(); // If response is a JSON use json()
if (body) {
return body.data || body;
} else {
return {};
}
}
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
Note .get()
instead of .request()
.
I wanted to also provide you extra extractData
and handleError
methods in case you need them and you don't have them.
This is work for me 100% :
let data:Observable<any> = this.http.post(url, postData);
data.subscribe((data) => {
let d = data.json();
console.log(d);
console.log("result = " + d.result);
console.log("url = " + d.image_url);
loader.dismiss();
});
Unfortunately, many of the answers simply indicate how to access the Response’s body as text. By default, the body of the response object is text, not an object as it is passed through a stream.
What you are looking for is the json() function of the Body object property on the Response object. MDN explains it much better than I:
The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.
response.json().then(function(data) { console.log(data);});
or using ES6:
response.json().then((data) => { console.log(data) });
Source: https://developer.mozilla.org/en-US/docs/Web/API/Body/json
This function returns a Promise by default, but note that this can be easily converted to an Observable for downstream consumption (stream pun not intended but works great).
Without invoking the json() function, the data, especially when attempting to access the _body property of the Response object, will be returned as text, which is obviously not what you want if you are looking for a deep object (as in an object with properties, or than can’t be simply converted into another objected).
Example of response objects
I had the same issue too and this worked for me try:
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res) => {
let resSTR = JSON.stringify(res);
let resJSON = JSON.parse(resStr);
console.log(resJSON._body);
})