Angular:Http vs获取API [英] Angular: Http vs fetch api

查看:61
本文介绍了Angular:Http vs获取API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我了解Angular发出HTTP请求的方式,但我更喜欢使用内置的Fetch API,因为我不必只订阅和取消订阅一个简单的请求.我尝试在我的有角度的应用程序中使用它,它没有引发任何错误,页面没有重新加载(仍然是SPA),一切正常.我想一切都有时间和地点.

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.

此:

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

比这更简单:

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

基本上我的问题是,在开发Angular应用程序时使用Fetch API是否错误?

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

推荐答案

就像您在开发过程中遇到的任何工具一样,每种工具都有其优点和缺点,最好考虑一下为什么要使用该工具.

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.

当我们看一下HttpClient时,它最初简化了XMLHttpRequest的混乱.与最初使用$.ajax的方式相同,HttpClient是角度解".它遵循了一切都是可观察对象的思想,它具有优点(可以将其与其他可观察对象混合并匹配)和缺点(它会增加很多膨胀).

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

  • 它允许轻松混合和匹配两个可观察对象(例如,假设您有一个可观察对象返回多次,而API请求则返回一次,并且您想将两者压缩在一起很容易).当然,将承诺变成可观察的仅需要从rxjs
  • 导入from
  • 如果您忘记添加抽象-所有请求都通过apiService层-您仍然可以使用拦截器神奇地获得相似的结果.
  • 它将为新的Angular开发人员增加学习曲线,从而使您的工作更加特别.
  • HttpClient为您做了一些魔术,例如自动重试请求.
  • 它已经包含在Angular中,因此,如果您需要支持7年之久的浏览器(如IE11),则无需像fetch那样加载polyfill.
  • 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.

重要:所有与提取相关的代码均假定您确实创建了非常简单的抽象(例如,在这些示例中为apiService).这与在HttpClient -land中设置拦截器相同.

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.

  • 这是新的行业标准.一旦知道它,它便可以在任何地方使用(很可能是Angular和React死了-在某些时候它们-fetch仍然很可能会出现).
  • 由于RequestResponse对象与您在常规代码中使用的对象相同,因此简化了与服务人员的合作.
  • HTTP请求通常仅返回一次(当然,您可能正在逐块加载文件,但这是该规则中非常罕见的例外). fetch是围绕规范(单个返回值)而不是异常(多个返回值)构建的,因此返回Promise而不是类似流的类型.这样做的好处是,它可以很好地与任何及所有相关的新语言功能(例如asyncawait)配合使用.比较:

  • 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');

使用

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

(当然,您也可以toPromise每个将完成的Observable(或添加.pipe(take(1)),但坦白地说,这是一堆多余的代码(我经常经常使用))

(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');

来自任何框架的开发人员都可以使用鼠标右键单击.get并检查函数定义,在该函数定义中将清楚地定义要添加的域和身份验证标头之类的东西.

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')

除非他们知道特定于Angular的魔术,否则他无法轻松地发现是否可能更改请求以及更改请求的位置.这就是为什么Angular的学习曲线陡峭的原因之一.

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

不会有您不知道的魔法,例如自动重试请求,最终可能导致同一请求在服务器上触发4次,并且您不知道这是怎么回事./p>

  • 它已经包含在浏览器中-如果您不需要支持7年以上的浏览器-那么它可以使捆绑包的尺寸略小.
  • 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.

    • 我真不明白类型之间的区别,因为可以通过任何方法键入返回值. <Model>this.apiService.get('/posts')可以很好地工作.
    • 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.

    就个人而言,我强烈建议任何人将fetch与抽象层配合使用.这样可以使代码更容易阅读(即使是从未见过asyncawait的初中生也可以阅读),即使您处于极少数情况下,您的apiService必须多次返回,您仍然可以完全自由地这样做,因为您完全可以控制.通常,如果替代方法具有明显的优势,则仅使用标准(fetch).即使就优缺点而言,这是一条完美的纽带,但对于特定于框架"的解决方案来说,还是不值得的.

    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似乎并没有提供任何明显的优势,除了在您不需要为API请求设置抽象层的初始项目设置过程中节省几分钟的时间之外.

    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.

    这篇关于Angular:Http vs获取API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆