Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: How to access an HTTP response body?

I wrote the following code in Angular 2:

this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').       subscribe((res: Response) => {         console.log(res);       }) 

When I print the response I get in console: enter image description here

I want to have access in the code to body field in the response. The 'body' field starts with an underscore, which means that it's a private field. When I change it to 'console.log(res._body)' I got an error.

Do you know any getter function that can help me here?

like image 465
CrazySynthax Avatar asked Apr 13 '17 13:04

CrazySynthax


People also ask

Can we send request body in GET request in Angular?

Just to clarify some of the answers here, firstly, as stated Angular does not support supplying a body with a GET request, and there is no way around this. The reason for that is not Angular's fault but that of XMLHttpRequest (XHR), the API that browsers use for making requests.

What does HTTP GET return in Angular?

get() method is an asynchronous method that performs an HTTP get request in Angular applications and returns an Observable. And that Observable emits the requested data when the response is received from the server.

Does Angular HttpClient use Fetch?

Angular offers HttpClient to work on API and handle data easily. In this approach HttpClient along with subscribe() method will be used for fetching data.


1 Answers

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.

like image 93
OrangeDog Avatar answered Oct 14 '22 21:10

OrangeDog