Angular 2: How to access an HTTP response body?
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
.
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)}) }}
Here is an example of a get
http call:
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);}
Note .get()
instead of .request()
.
I wanted to also provide you extra extractData
and handleError
methods in case you need them and you don't have them.