如果可能,我应该使用angularjs $ http服务请求或jquery ajax吗? [英] Should I use angularjs $http service for requests or jquery ajax if possible?

查看:61
本文介绍了如果可能,我应该使用angularjs $ http服务请求或jquery ajax吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,每当我进行ajax调用时,我都会使用angularjs框架并喜欢使用 $ http 服务。但是在项目的某些部分,如果没有通过ajax调用直接更新UI并且不需要angularjs绑定,我应该使用 $ http 服务还是普通 jquery.ajax

In my project, I use angularjs framework and love using the $http service whenever I make an ajax call. But in parts of the project, where an UI is not directly updated by the ajax call and angularjs bindings are not required, should I use $http service or plain jquery.ajax?

更具体地说,我应该最小化我不关心UI的项目中的angularjs依赖关系,还是用angular服务和指令紧紧包裹整个项目?

More specifically speaking, should I minimize angularjs dependencies in my project where UI is not concerned or tightly wrap the whole project with angular services and directives?

推荐答案

如果您使用的是Angularjs,那么您应该使用$ http作为进行ajax调用的首选方法。
没有必要将该服务绑定到ui或影响ui。

If you are using Angularjs, then you should use $http as the preferred method of making the ajax calls. It is not necessary for that service to be binded to ui or be affecting ui.

只有在无法执行时才应使用Jquery Ajax调用使用角度服务的操作,如果你遵循angularjs最佳实践,这种情况很少见。

You should use Jquery Ajax calls only when you are unable to perform the action using angular services which will be rare if you follow angularjs best practices.

此外,如果你使用http服务,你可以让拦截器在它们出现之前创建请求并处理响应。给成功部分召唤。这些用于处理全局错误和显示全局通知,可以说,可以进行任何响应。此外,您可以在每个请求之前添加标题和更多信息。此外,您可以在此处对请求/响应进行编码/解码,以便所有这些实用程序功能都在同一位置完成。请查看以下链接:
带拦截器的http服务文档

Also if you use http services, you can have intercepters that creates requests and processes response before they are given to success part of the call. These are used for handling global errors and displaying global notifications which let's say, can come in any response. Plus you can add headers and more info before each request here. Also you can encode/decode the request/response here such that all these utility functions are done at the same place. Check the below link for this: http service doc with interceptors

如果你仍然需要从外部角度环境中调用$ http,你应该尽量避免使用它,做一个角度的常用效用函数并将其包装在一些函数中你可以直接打电话。

If still you need to call the $http from outside angular environment, which you should try to avoid, make a common utility function of angular and wrap it in some function that you can call directly.

这篇关于如果可能,我应该使用angularjs $ http服务请求或jquery ajax吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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