Angular 2:如何访问HTTP响应体?

53

我用Angular 2编写了以下代码:

this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
      subscribe((res: Response) => {
        console.log(res);
      })

当我在控制台中打印响应时:

enter image description here

我想要在代码中访问响应中的正文字段。'body'字段以下划线开头,这意味着它是一个私有字段。 当我将其更改为 'console.log(res._body)'时,出现了错误。

你知道有什么getter函数可以帮助我吗?


点击这里,https://dev59.com/BVcQ5IYBdhLWcg3wA_TH#44622319,然后你可以使用`res.json().results`来获取返回的数组。 - Belter
12个回答

65

RequestResponse 都扩展了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


2
response.text(),编译器本身会抱怨对象不存在text()方法。 - Jess
请回复@Jess。 - olajide
@Jess 也许你没有使用 Angular 2? - OrangeDog
@OrangeDog,是的,我正在使用Angular7。 - Jess
.body() 对我没用,但 .text() 有用。记下可能需要在将来更改。 - Peter Meadley

20

以下是一个使用 Angular2 内置的 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)})

  }
}

11

这里是一个 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()

如果需要,我还会提供额外的extractDatahandleError方法。


我已经更新了我的答案,使用text()代替json() - SrAxi

5
我也遇到过同样的问题,以下方法对我有用,请尝试:

我也遇到了同样的问题,这个方法对我有效,请尝试:

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);
  })

5

1
出现错误: 类型“Observable<Response>”上不存在属性“map”。 - CrazySynthax
尝试导入'rxjs/add/operator/map'。 - Dmitrij Kuba

4
.subscribe(data => {   
            console.log(data);
            let body:string = JSON.parse(data['_body']);`

4
尽管这可能回答了问题,但最好解释答案的基本部分,并可能解释OP代码的问题。 - pirho

4
很不幸,许多答案只是指示如何将响应的正文作为文本访问。默认情况下,响应对象的正文是文本,而不是像通过流一样的对象。
你要找的是响应对象上Body对象属性的json()函数。 MDN更好地解释了它:
Body mixin的json()方法接受一个Response流并读取其完成。 它返回一个Promise,该Promise解析为将正文文本解析为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属性时,将会以文本形式返回,如果您正在寻找一个深层次的对象(如具有属性或不能简单地转换为另一个对象的对象),这显然不是您想要的。

响应对象示例


4

你不能直接引用_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;
            });

工作中的示例代码


1
是的,这通常是我做事的方式。我甚至在Pluralsight课程中看到过这种方法。这是我选择的正确答案。 - Eric Bishard
为什么要使用返回其参数的映射函数?这不会完全没有任何效果吗? - Kevin Beal

2
您可以尝试使用HttpResponse @angular/common/http。
订阅((res:HttpResponse )=> { console.log(res.body)})
不要忘记导入import {HttpResponse} from'@ angular / common / http';

HttpResponse<any> 中使用 any 有更好的选项吗? - greenchapter
使用 HttpResponseBase - greenchapter

1

以下代码适用于所有版本的Angular:

let body = JSON.parse(JSON.stringify(response)).body;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接