【问题标题】:In Angular 2 what does response.json() do?在 Angular 2 中 response.json() 做什么?
【发布时间】:2017-11-22 08:52:48
【问题描述】:

这是来自 app/toh/hero.service.ts 的 angular 2 http 指南:

...
@Injectable()
export class HeroService {
  private heroesUrl = 'app/heroes';  // URL to web API
  constructor (private http: Http) {}
  getHeroes (): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }
  private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }
  private handleError (error: Response | any) {
   ...
  }

}

请参考 let body = res.json(); 从 API 我在 Response 对象上找不到任何 json() 方法。 从响应源我确实找到了这个:

export var Body = (function () {
    function Body() {
    }
    /**
     * Attempts to return body as parsed `JSON` object, or raises an exception.
     */
    Body.prototype.json = function () {
        if (isString(this._body)) {
            return Json.parse(this._body);
        }
        if (this._body instanceof ArrayBuffer) {
            return Json.parse(this.text());
        }
        return this._body;
    };

这两个有什么关系?

【问题讨论】:

  • 什么不清楚? .json 方法尝试为您将响应正文解析为 JS 对象。 here 提到 “Angular HTTP 客户端遵循 Fetch 规范”
  • 返回Response的解析数据...
  • @johnsharpe,可能我的问题措辞不正确。我想知道在“响应”源代码中哪里可以找到 json() 方法。我在“正文”源代码中找到了该方法。我正在回答我自己的问题,请仔细阅读,如果您发现我的任何误解,请指出。

标签: javascript angular


【解决方案1】:

我查看了 node_modules/@angular/http/src 并一直在寻找

导出变量响应

在文件 static_response.js 中找到。它说:

export var Response = (function (_super) {
__extends(Response, _super);
function Response(responseOptions) {
    _super.call(this);
    this._body = responseOptions.body;
    this.status = responseOptions.status;
    this.ok = (this.status >= 200 && this.status <= 299);
    this.statusText = responseOptions.statusText;
    this.headers = responseOptions.headers;
    this.type = responseOptions.type;
    this.url = responseOptions.url;
}
Response.prototype.toString = function () {
    return "Response with status: " + this.status + " " + this.statusText + " for URL: " + this.url;
};
return Response;
}(Body));

在同一个文件中,__extends 定义如下:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};

所以 Body 有 json() & Response 通过复制从 Body 中获取。

【讨论】:

    【解决方案2】:

    只需使用 json() 映射您的响应

    this.jsonp.get("http://localhost:8080/api/getpost") 
              .map(res => res.json()) 
              .subscribe(data => console.log(data));
    

    【讨论】:

      猜你喜欢
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 1970-01-01
      • 2023-03-09
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多