在 Angular 中使用 `fetch`

Using `fetch` in Angular

使用本机 Fetch API 而不是 Angular 中的 HttpClient 是否有任何特定的技术缺陷?我对 Angular 比较陌生,不确定以这种方式 'circumvent' 提供的接口是否安全。 (例如,根据 documentation,通过访问 document 直接修改 DOM 似乎是不可取的。)

我正在使用 Angular 6,我不担心不支持 fetch 的客户端。

Angular 是一个 固执己见的 框架——这意味着该框架希望您以 Angular 的方式做事。这并不意味着您必须按照他们的方式做事。

自由使用fetch()httpClient。它们是解决同一问题的两种不同方法,您应该根据您的需要选择一种。

使用 fetch() 将 return 一个承诺。使用 Angular 的 httpClient 将 return 一个 Observable,它具有 Promises 没有的特性。您可以使用 Observable.toPromise() 转换它,但是...为什么要使用 Observable?

这就是 Angular 希望您使用 httpClient 的原因:

Additional benefits of HttpClient include testability features, typed request and response objects, request and response interception, Observable apis, and streamlined error handling.

如其他答案所述,HttpClient 库还有其他好处,正如我在下面读到的 link,它还可以通过考虑一些方法来帮助预防 XSSI 攻击:

Angular's HttpClient library recognizes this convention and automatically strips the string ")]}',\n" from all responses before further parsing.

Angular Security - XSSI