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

Cra*_*hax 39 javascript ajax http angular

我在Angular 2中编写了以下代码:

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

当我打印响应时,我进入控制台: 在此输入图像描述

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

你知道任何可以帮助我的吸气功能吗?

Sto*_*ica 56

两者RequestResponse延伸Body.要获取内容,请使用该text()方法.

this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10')
    .subscribe(response => console.log(response.text()))
Run Code Online (Sandbox Code Playgroud)

  • respone.text() ,编译器本身抱怨该对象不存在 text() 。 (2认同)

小智 15

下面是一个例子访问使用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)})

  }
}
Run Code Online (Sandbox Code Playgroud)


SrA*_*Axi 11

以下是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);
}
Run Code Online (Sandbox Code Playgroud)

注意.get()而不是.request().

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


小智 5

响应数据采用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);
  })
Run Code Online (Sandbox Code Playgroud)

https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data


小智 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);
  })
Run Code Online (Sandbox Code Playgroud)


kin*_*ser 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;
            });
Run Code Online (Sandbox Code Playgroud)

工作笨蛋