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.

5
  • 1
    You can definitely go ahead and use it Commented Sep 8, 2018 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.) Commented Sep 8, 2018 at 17:24
  • 1
    Also I think if your using angular 6 and enable the polyfill , angular will generate the polyfill for fetch Commented Sep 8, 2018 at 17:31
  • @T.J.Crowder Thank you. I have made another edit to clarify what I was thinking about. Commented Sep 8, 2018 at 17:32
  • Handling errors with fetch is more tedious though, requires some extra effort. Refer this article for making more sound decision, css-tricks.com/using-fetch Commented Sep 8, 2018 at 18:06

2 Answers 2

18

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.

Sign up to request clarification or add additional context in comments.

Comments

-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

1 Comment

-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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.