Angular 2:如何访问 HTTP 响应正文? [英] Angular 2: How to access an HTTP response body?
问题描述
我在 Angular 2 中编写了以下代码:
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:
我想在代码中访问响应中的正文字段.'body' 字段以下划线开头,这意味着它是一个私有字段.当我将其更改为 'console.log(res._body)' 时,出现错误.
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.
你知道任何可以帮助我的 getter 函数吗?
Do you know any getter function that can help me here?
推荐答案
Both Request
和 Response
扩展 正文
.要获取内容,请使用 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
类有一个 .body()
方法.使用 {responseType: 'text'}
应该返回一个 String
.
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
.
这篇关于Angular 2:如何访问 HTTP 响应正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!