[英]Angular 2: How to access an HTTP response body?
我在 Angular 2 中编写了以下代码:
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res: Response) => {
console.log(res);
})
我想在代码中访问响应中的 body 字段。 'body' 字段以下划线开头,这意味着它是一个私有字段。 当我将其更改为 'console.log(res._body)' 时,出现错误。
你知道任何可以在这里帮助我的getter函数吗?
Request
和Response
扩展了Body
。 要获取内容,请使用text()
方法。
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10')
.subscribe(response => console.log(response.text()))
该 API 在 Angular 5 中已弃用。新的HttpResponse<T>
类改为具有.body()
方法。 使用{responseType: 'text'}
应该返回一个String
。
这是一个使用 Angular2内置响应访问响应正文的示例
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)})
}
}
下面是一个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);
}
注意.get()
而不是.request()
。
我还想为您提供额外的extractData
和handleError
方法,以防您需要它们而您没有它们。
响应数据采用 JSON 字符串形式。 应用程序必须通过调用 response.json() 将该字符串解析为 JavaScript 对象。
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
.map(res => res.json())
.subscribe(data => {
console.log(data);
})
https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data
我也有同样的问题,这对我有用,请尝试:
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res) => {
let resSTR = JSON.stringify(res);
let resJSON = JSON.parse(resStr);
console.log(resJSON._body);
})
不能直接引用_body
对象吗? 显然,如果以这种方式使用,它不会返回任何错误。
this.http.get('https://thecatapi.com/api/images/get?format=html&results_per_page=10')
.map(res => res)
.subscribe(res => {
this.data = res._body;
});
不幸的是,许多答案只是指出如何以text 形式访问 Response 的 body 。 默认情况下,响应对象的主体是文本,而不是通过流传递的对象。
您正在寻找的是 Response 对象上 Body 对象属性的 json() 函数。 MDN 解释得比我好得多:
Body mixin 的json()方法接受一个 Response 流并读取它完成。 它返回一个承诺,该承诺将正文文本解析为 JSON 的结果进行解析。
response.json().then(function(data) { console.log(data);});
或使用 ES6:
response.json().then((data) => { console.log(data) });
来源: https : //developer.mozilla.org/en-US/docs/Web/API/Body/json
默认情况下,此函数返回一个 Promise,但请注意,这可以轻松转换为 Observable 以供下游消费(流双关语不是故意的,但效果很好)。
在不调用 json() 函数的情况下,数据,尤其是在尝试访问 Response 对象的 _body 属性时,将作为文本返回,如果您正在寻找深层对象(如在对象中),这显然不是您想要的属性,或者不能简单地转换为另一个对象)。
.subscribe(data => {
console.log(data);
let body:string = JSON.parse(data['_body']);`
下面一个将适用于所有版本的 Angular:
let body = JSON.parse(JSON.stringify(response)).body;
您可以尝试使用 HttpResponse @angular/common/http。
subscribe((res: HttpResponse<any>) => { console.log(res.body) })
不要忘记import { HttpResponse } from '@angular/common/http';
导入import { HttpResponse } from '@angular/common/http';
这对我来说是 100% 的工作:
let data:Observable<any> = this.http.post(url, postData);
data.subscribe((data) => {
let d = data.json();
console.log(d);
console.log("result = " + d.result);
console.log("url = " + d.image_url);
loader.dismiss();
});
这应该有效。 如果是 json 响应,您可以使用 response.json() 获取 body。
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res: Response.json()) => {
console.log(res);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.