Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `fetch` in Angular [duplicate]

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.

like image 963
黄雨伞 Avatar asked Sep 08 '18 17:09

黄雨伞


1 Answers

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.

like image 53
Taylor Krusen Avatar answered Sep 23 '22 14:09

Taylor Krusen