Angular Response.json()没有记录

BBa*_*ger 22 json angular

我看到Response.json()方法被大量使用,我自己也在使用它,但要么我缺少某些内容,要么Response类的文档不正确.

例:

getCurrentTime() {
    return this._http.get('http://date.jsontest.com/')
        .map((res:Response) => res.json())
}
Run Code Online (Sandbox Code Playgroud)

在Angular网站https://angular.io/docs/ts/latest/api/http/index/Response-class.html上,我没有看到该方法是Response类的成员.

如果.json 不是 Response类的成员,那么有人可以指出我理解其工作原理的方向.

或者如果文档有误,请有人这样说.

提前致谢.

Pau*_*tha 19

我看一下响应API参考,你会看到Response扩展Body.如果你试图搜索Body,你将找不到它,这可能意味着它不公开.如果您查看Body的源代码,您将看到代码json

/**
 * Attempts to return body as parsed `JSON` object, or raises an exception.
 */
json(): any {
  if (typeof this._body === 'string') {
    return JSON.parse(<string>this._body);
  }

  if (this._body instanceof ArrayBuffer) {
    return JSON.parse(this.text());
  }

  return this._body;
}
Run Code Online (Sandbox Code Playgroud)

如果您需要解释来源,请告诉我.尽管如此,它看起来很自我解释.


nae*_*th7 10

实际上,HTTP Client文档(处理响应对象)说:

解析为JSON

这不是Angular自己的设计.Angular HTTP客户端遵循Fetch函数返回的响应对象的Fetch规范.该规范定义了一个json()将响应主体解析为JavaScript对象的方法.

所以Angular2实现了Fetch规范,其中包含了上述Bodymixin的规范,Angular2的Response类正在扩展,包括.json()方法.

json()调用该方法时,必须返回使用JSON运行使用体的结果.

正如你在peeskillet的链接中看到的那样,Angular2正在实现Body mixin的所有指定方法,除了formData().