10

Is there any specific technical drawback to using the native Fetch API rather than HttpClient in Angular? I'm relatively new to Angular, and unsure about whether it's safe to 'circumvent' the provided interfaces in such a way. (As an example, it seems directly modifying the DOM by accessing document is not advisable, according to the documentation.)

I'm using Angular 6, and I'm not concerned about clients that don't support fetch.

黄雨伞
  • 1,904
  • 1
  • 16
  • 17
  • 1
    You can definitely go ahead and use it – brk Sep 08 '18 at 17:22
  • 1
    @ 黄雨伞 - I've done a minor edit to try to make the question not opinion-based. But if you disagree with the edit, feel free to roll it back. (Note that the question may then be closed as off-topic based on opinion.) – T.J. Crowder Sep 08 '18 at 17:24
  • 1
    Also I think if your using angular 6 and enable the polyfill , angular will generate the polyfill for fetch – brk Sep 08 '18 at 17:31
  • @T.J.Crowder Thank you. I have made another edit to clarify what I was thinking about. – 黄雨伞 Sep 08 '18 at 17:32
  • Handling errors with fetch is more tedious though, requires some extra effort. Refer this article for making more sound decision, https://css-tricks.com/using-fetch/ – S. Patel Sep 08 '18 at 18:06

2 Answers2

17

Angular is an opinionated framework—meaning the framework wants you to do things the Angular way. That doesn't mean you have to do things their way.

Use either the fetch() or the httpClient freely. They're two different approaches to the same problem and you should pick one based on the context of your needs.

Using fetch() will return a promise. Using Angular's httpClient will return an Observable, which has features that Promises don't. You can convert it with Observable.toPromise(), but then... why use an Observable?

Here's why Angular wants you to use httpClient:

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

Taylor Krusen
  • 963
  • 6
  • 10
-1

As said in other answers, HttpClient library has additional benefits and as I read in below link, it also can help for prevention of XSSI attacks by considering some methods:

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

Angular Security - XSSI

Jalaleddin Hosseini
  • 2,142
  • 2
  • 25
  • 28
  • 1
    -1 Because that stripping is simply a convention used to prevent parsing in very old browsers. Something that only applies if you actively include exactly that in your JSON responses... in which case you could just as easily go for `fetch` and take out that string yourself in some API calling layer. – David Mulder May 06 '20 at 06:46