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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43394144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:54:15  来源:igfitidea点击:

Angular 2: How to access an HTTP response body?

javascriptajaxangularhttp

提问by CrazySynthax

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: enter image description here

当我打印响应时,我在控制台中得到: 在此处输入图片说明

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.

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

Do you know any getter function that can help me here?

你知道任何可以在这里帮助我的getter函数吗?

回答by OrangeDog

Both Requestand Responseextend Body. To get the contents, use the text()method.

无论RequestResponse扩展Body。要获取内容,请使用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. With a {responseType: 'text'}that should return a String.

该 API 在 Angular 5 中已被弃用。新HttpResponse<T>类改为有一个.body()方法。使用 a{responseType: 'text'}应该返回 a String

回答by vishnu

Here is an example to access response body using angular2built 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)})

  }
}

回答by SrAxi

Here is an example of a gethttp call:

下面是一个gethttp 调用的例子:

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 extractDataand handleErrormethods in case you need them and you don't have them.

我想还为您提供额外的extractDatahandleError在方法的情况下,你需要他们,你没有这些。

回答by Dmitrij Kuba

The response data are in JSON string form. The app must parse that string into JavaScript objects by calling response.json().

响应数据采用 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

回答by A. Bahieddine

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

回答by pinky00106

Unfortunately, many of the answers simply indicate how to access the Response's body as text. By default, the body of the response object is text, not an object as it is passed through a stream.

不幸的是,许多答案只是指出如何以text 形式访问 Response 的 body 。默认情况下,响应对象的主体是文本,而不是通过流传递的对象。

What you are looking for is the json() function of the Body object property on the Response object. MDN explains it much better than I:

您正在寻找的是 Response 对象上 Body 对象属性的 json() 函数。MDN 解释得比我好得多:

The json()method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

Body mixin的json()方法接受一个 Response 流并读取它完成。它返回一个承诺,该承诺将正文文本解析为 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

响应对象示例

回答by RUPNESH SHARMA

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

回答by kind user

Can't you just refer to the _bodyobject directly? Apparently it doesn't return any errors if used this way.

不能_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;
            });

Working plunker

工作笨蛋

回答by Nheom Phearum

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

回答by himanshu goyal

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