Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - Angular: Http vs fetch api

Although I understand the way Angular makes HTTP requests, I prefer using the built-in Fetch API because I don't have to subscribe and unsubscribe just to make 1 simple request. I tried using it in my angular app and it didn't throw any errors, page didn't reload (still a SPA), everything worked fine. I suppose there is a time and place for everything.

This:

fetch('/api/get_post_by_id/1').then(r => r.json()).then(j => { console.log(j); });

Is more simple, than this:

const obs = this.http.get('/api');
obs.subscribe(() => { ... });
obs.unsubscribe();

Basically my question is, is it wrong to use the Fetch API when developing Angular apps?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like any tool you encounter during development each tool will have advantages and disadvantages and it's good to think about why a tool is being used.

When we take a look at HttpClient it originally simplified the mess that was XMLHttpRequest. In the same way $.ajax originally did it, HttpClient was the 'angular solution'. It followed the ideology of everything being an observable which has advantages (you can mix and match it with other observables) and disadvantages (it adds a lot of bloat).

Advantages of HttpClient

  • It allows easy mixing and matching of two observables (e.g. let's say you have one observable which returns multiple times and an API request which returns once and you want to zip the two together it's trivially easy to do). Of course, turning a promise into an observable only requires importing from from rxjs
  • If you forget adding an abstraction - having all requests going through an apiService layer - you can still use an interceptor to achieve similar results magically.
  • It will increase the learning curve for new Angular developers, thus making your job more special.
  • HttpClient does some magic for you such as automatic retrying of requests.
  • It's already included in Angular, so if you need to support 7 year old browsers like IE11 you don't need to load a polyfill like with fetch.

Advantages of fetch

Important : All fetch related code assumes you do create a very simple abstraction (e.g. apiService in these examples). This is the same as setting up an interceptor in HttpClient-land.

  • It's the new industry standard. Once you know it, it can be used anywhere (most likely once Angular and React die - which at some point they will - fetch will still most likely be around).

  • It simplifies working with service workers as the Request and Response objects are the same you are using in your normal code.

  • HTTP requests will typically return once and only once (of course you might be loading a file chunk by chunk, but that's a very rare exception to the rule). fetch is built around the norm (single return values), not the exception (multiple return values), and thus returns a Promise rather than a stream-like-type. The advantage this results in is that it plays nicely with any and all relevant new language features such as async and await. Compare:

     try {
         const posts = await this.apiService.get('/posts');
         // work with posts
     } catch (error) {
         // handle error
     }
     console.log('this happens **after** the request completes');
    

    with

     this.http.get('/posts')
         .subscribe(posts => {
             // work with posts
         })
         .catch(error => {
             // work with error
         });
     console.log('this happens **before** the request completes');
    

    (of course you can also toPromise each Observable that will complete (or add .pipe(take(1)), but that's frankly a bunch of superfluous code (which I still often end up using))

  • It simplifies onboarding of new people. When you see a request such as

     this.apiService.get('/posts');
    

    a developer from any framework can come and right-click on .get and check out the function definition where things such as a domain and an authentication header being added will be clearly defined.

    On the other hand when a developer sees

     this.http.get('/posts')
    

    they have no way of easily discovering if and where the request might be changed unless they are aware of Angular specific magic. This is one of the reasons why Angular is considered to have a steep learning curve.

  • There is no risk of there being magic you aren't aware of such as automatic retrying of requests which can end up in the same request triggering 4 times on the server and you having no idea how that's possible.

  • It's already included in the browser - provided you don't need to support 7 year old browsers - so it can result in a slightly smaller bundle size.

Complete tie

  • I sincerely don't see how types are a difference, as typing a return value from any method can be done. <Model>this.apiService.get('/posts') works perfectly fine.

Conclusion

Personally, I would strongly recommend anybody to use fetch with an abstraction layer. It results in easier to read code (even a junior who hasn't ever seen async and await is able to read it) and even if you are in a rare situation where your apiService has to return multiple times you are still completely free to do so as you're fully in control. And in general, you should only not use the standard (fetch) if the alternative offers significant advantages. Even if it was a perfect tie in terms of advantages and disadvantages it probably isn't worth going for a 'framework specific' solution.

HttpClient just doesn't seem to offer any tangible advantages beyond saving a couple of minutes of time during the initial project setup where you don't need to set up an abstraction layer for API requests.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...