棱角是否真的遵循fetch的规格?

时间:2017-06-23 16:27:15

标签: javascript angular http fetch

Angular的http文档说明http服务返回的响应遵循fetch规范。

https://angular.io/guide/http#parse-to-json

在他们的示例中,这是您可以找到的代码

private extractData(res: Response) {
  let body = res.json();
  return body.data || { };
}

显然,res.json()的结果不是承诺

但是在fetch规范中,response.json()方法应该返回Promise

https://fetch.spec.whatwg.org/#response-class

我是否遗漏了fetch规范中的内容或Angular对其实施的错误?

2 个答案:

答案 0 :(得分:1)

查看有角度的http来源,很明显它没有回复承诺:

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

  // source https://github.com/angular/angular/blob/master/packages/http/src/body.ts#L26

但规范说

[NoInterfaceObject, Exposed=(Window,Worker)]
interface Body {
  readonly attribute ReadableStream? body;
  readonly attribute boolean bodyUsed;
  [NewObject] Promise<ArrayBuffer> arrayBuffer();
  [NewObject] Promise<Blob> blob();
  [NewObject] Promise<FormData> formData();
  [NewObject] Promise<any> json();
  [NewObject] Promise<USVString> text();
};

因此,似乎角度决定不严格遵守规范。

答案 1 :(得分:1)

我认为你是对的(因为consume body algo),他们没有遵循fetch的规范,他们在内部使用JSON.parse来解析JSON (见:github)。

我认为他们这样做是为了更容易地将错误传播到callstack,因此用户可以通过http.get().catch()轻松捕获它。但是有关更多信息,请尝试通过gitter直接询问他们。