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:
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?
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With