How to use the Fetch API in Angular
How to use the Fetch API to make network requests in Angular rather than using the built-in xhr service.
The reason I did this was to understand how Angular creates network requests in the internal workings. I’ve been developing in React for the last few years and wondered why Angular does not use Fetch when returning to Angular.
I don’t think there is a reason to use Fetch in Angular as the existing xhr service is fine. There are pro and cons with both which are already well documented on the internet so will not cover that here.
You can see the Angular xhr backend service here.
I’ve used fromFetch
from the RxJS library to handle aborting and emitting the response from Fetch. I also copied the xhr tests from the Angular repo and updated the tests to pass without changing the assertions, I couldn't replicate everything, but I feel I covered the important tests.
You should be able to provide the Fetch service in one of your Angular modules and you won’t need to make any changes to your existing requests/interceptors that use the httpClient, your tests will also work as before as the HttpClientTestingModule uses its own HttpBackend
Questions, comments and improvements are very welcome.
Many thanks for reading and the fetch service can be found below — there is also an example repo with tests which can be found here.