Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
Angular 2: ¿Cómo acceder a un cuerpo de respuesta HTTP?

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: ingrese la descripción de la imagen aquí

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í?

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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 .

about 4 years ago · Santiago Trujillo Report

0

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)}) } }
about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!