简体   繁体   English

Angular 2:如何访问 HTTP 响应正文?

[英]Angular 2: How to access an HTTP response body?

I wrote the following code in Angular 2:我在 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:当我打印响应时,我在控制台中得到: 在此处输入图片说明

I want to have access in the code to body field in the response.我想在代码中访问响应中的 body 字段。 The 'body' field starts with an underscore, which means that it's a private field. 'body' 字段以下划线开头,这意味着它是一个私有字段。 When I change it to 'console.log(res._body)' I got an error.当我将其更改为 'console.log(res._body)' 时,出现错误。

Do you know any getter function that can help me here?你知道任何可以在这里帮助我的getter函数吗?

Both Request and Response extend Body . RequestResponse扩展了Body To get the contents, use the text() method.要获取内容,请使用text()方法。

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.该 API 在 Angular 5 中已弃用。新的HttpResponse<T>类改为具有.body()方法。 With a {responseType: 'text'} that should return a String .使用{responseType: 'text'}应该返回一个String

Here is an example to access response body using angular2 built in Response这是一个使用 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)})

  }
}

Here is an example of a get http call:下面是一个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);
}

Note .get() instead of .request() .注意.get()而不是.request()

I wanted to also provide you extra extractData and handleError methods in case you need them and you don't have them.我还想为您提供额外的extractDatahandleError方法,以防您需要它们而您没有它们。

The response data are in JSON string form.响应数据采用 JSON 字符串形式。 The app must parse that string into JavaScript objects by calling response.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 https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data

I had the same issue too and this worked for me try:我也有同样的问题,这对我有用,请尝试:

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

Can't you just refer to the _body object directly?不能直接引用_body对象吗? Apparently it doesn't return any errors if used this way.显然,如果以这种方式使用,它不会返回任何错误。

this.http.get('https://thecatapi.com/api/images/get?format=html&results_per_page=10')
            .map(res => res)
            .subscribe(res => {
                this.data = res._body;
            });

Working plunker工作笨蛋

Unfortunately, many of the answers simply indicate how to access the Response's body as text .不幸的是,许多答案只是指出如何以text 形式访问 Response 的 body 。 By default, the body of the response object is text, not an object as it is passed through a stream.默认情况下,响应对象的主体是文本,而不是通过流传递的对象。

What you are looking for is the json() function of the Body object property on the Response object.您正在寻找的是 Response 对象上 Body 对象属性的 json() 函数。 MDN explains it much better than I: MDN 解释得比我好得多:

The json() method of the Body mixin takes a Response stream and reads it to completion. Body mixin 的json()方法接受一个 Response 流并读取它完成。 It returns a promise that resolves with the result of parsing the body text as JSON.它返回一个承诺,该承诺将正文文本解析为 JSON 的结果进行解析。

response.json().then(function(data) { console.log(data);});

or using ES6:或使用 ES6:

response.json().then((data) => { console.log(data) });

Source: https://developer.mozilla.org/en-US/docs/Web/API/Body/json来源: https : //developer.mozilla.org/en-US/docs/Web/API/Body/json

This function returns a Promise by default, but note that this can be easily converted to an Observable for downstream consumption (stream pun not intended but works great).默认情况下,此函数返回一个 Promise,但请注意,这可以轻松转换为 Observable 以供下游消费(流双关语不是故意的,但效果很好)。

Without invoking the json() function, the data, especially when attempting to access the _body property of the Response object, will be returned as text, which is obviously not what you want if you are looking for a deep object (as in an object with properties, or than can't be simply converted into another objected).在不调用 json() 函数的情况下,数据,尤其是在尝试访问 Response 对象的 _body 属性时,将作为文本返回,如果您正在寻找深层对象(如在对象中),这显然不是您想要的属性,或者不能简单地转换为另一个对象)。

Example of response objects响应对象示例

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

下面一个将适用于所有版本的 Angular:

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

You can try using HttpResponse @angular/common/http.您可以尝试使用 HttpResponse @angular/common/http。

subscribe((res: HttpResponse<any>) => { console.log(res.body) })

Don't forget to import import { HttpResponse } from '@angular/common/http';不要忘记import { HttpResponse } from '@angular/common/http';导入import { HttpResponse } from '@angular/common/http';

This is work for me 100% :这对我来说是 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();
});

This should work.这应该有效。 You can get body using response.json() if its a json response.如果是 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.

相关问题 如何访问 angular 中的 HTTP 错误响应正文 - How can I access HTTP error response body in angular 失败时如何从Angular HTTP Interceptor访问Response主体? - How to access Response body from Angular HTTP Interceptor on failure? Angular 7:如何从测试用例访问/发送HTTP响应的正文部分 - Angular 7: How to access/send only body part of HTTP Response from test case 如何在 angular 中访问 http 响应中的嵌套数组和对象 - How to access nested array and objects in http response In angular 如何在angular 2应用程序中从http json响应保存访问令牌? - How to save an access Token from a http json response in angular 2 app? "Chrome 扩展 - 如何获取 HTTP 响应正文?" - Chrome Extension - How to get HTTP Response Body? 从Angular 4 HTTP调用获得完整响应(不仅仅是正文) - Getting a Full Response (not just the body) from Angular 4 HTTP Calls 如何访问 Promise 响应正文中的 ReadableStream - how to access the ReadableStream inside of the body of the Promise response 如何将 HTTP 响应主体编码为 node.js 中的 UTF-8 - How to encode HTTP response body as UTF-8 in node.js 如果出现 HTTP 错误 422,如何使用 fetch 获取响应正文? - How to fetch response body using fetch in case of HTTP error 422?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM