Escribí el siguiente código en Angular 2:
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10'). subscribe((res: Response) => { console.log(res); })
Cuando imprimo la respuesta me sale en la consola:
Quiero tener acceso en el código al campo del cuerpo en la respuesta. El campo 'cuerpo' comienza con un guión bajo, lo que significa que es un campo privado. Cuando lo cambio a 'console.log(res._body)', aparece un error.
¿Conoces alguna función getter que pueda ayudarme aquí?
Tanto la Request
como la Response
extienden el Body
. Para obtener el contenido, use el método text()
.
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10') .subscribe(response => console.log(response.text()))
Esa API quedó obsoleta en Angular 5. La nueva clase HttpResponse<T>
en su lugar tiene un método .body()
. Con un {responseType: 'text'}
que debería devolver un String
.
Aquí hay un ejemplo para acceder al cuerpo de la respuesta usando angular2 construido en 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)}) } }
Aquí hay un ejemplo de una llamada get
http:
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); }
Tenga en cuenta .get()
en lugar de .request()
.
También quería proporcionarle métodos extractData
y handleError
adicionales en caso de que los necesite y no los tenga.