【问题标题】:Is angular really following the fetch's specifications?角度真的遵循 fetch 的规范吗?
【发布时间】:2026-01-30 21:25:01
【问题描述】:

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 的实现有误?

【问题讨论】:

    标签: javascript angular http fetch


    【解决方案1】:

    查看 Angular 的 http 源,很明显它没有返回 Promise:

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

    所以看来 angular 决定不严格遵守规范。

    【讨论】:

    • 确实这行规范令人困惑。在 MDN 中,它显然是一个承诺 developer.mozilla.org/en-US/docs/Web/API/Body/json,而在规范中,json 的签名是 [NewObject] Promise&lt;any&gt; json(); fetch.spec.whatwg.org/#body-mixin
    • 对我来说很清楚它必须返回一个 Promise。 Promise 是一个对象,每个 json() 调用都应该返回一个 NEW Promise obj,而不是相同的引用(如规范所述)。
    • 完全同意。 Angular 团队选择不返回承诺可能是有原因的。我可能会调查这件事:)
    【解决方案2】:

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

    我认为他们这样做是为了更容易地在调用堆栈中传播错误,因此用户可以通过http.get().catch() 自己轻松捕获它。但要了解更多信息,请尝试通过gitter 直接询问他们。

    【讨论】: