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
.subscribe(data => {
console.log(data);
let body:string = JSON.parse(data['_body']);`
Here is an example to access response body using angular2 built in Response
import { Injectable } from '@angular/core';
import {Http,Response} from '@angular/http';
@Injectable()
export class SampleService {
constructor(private http:Http) { }
getData(){
this.http.get(url)
.map((res:Response) => (
res.json() //Convert response to JSON
//OR
res.text() //Convert response to a string
))
.subscribe(data => {console.log(data)})
}
}
The response data are in JSON string form. The app must parse that string into JavaScript objects by calling response.json().
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
.map(res => res.json())
.subscribe(data => {
console.log(data);
})
https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data
This should work. You can get body using response.json() if its a json response.
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res: Response.json()) => {
console.log(res);
})
Both Request and Response extend Body.
To get the contents, use the text()
method.
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10')
.subscribe(response => console.log(response.text()))
That API was deprecated in Angular 5. The new HttpResponse<T> class instead has a .body()
method. With a {responseType: 'text'}
that should return a String
.
Can't you just refer to the _body
object directly? Apparently it doesn't return any errors if used this way.
this.http.get('https://thecatapi.com/api/images/get?format=html&results_per_page=10')
.map(res => res)
.subscribe(res => {
this.data = res._body;
});
Working plunker