Should I use angularjs $http service for requests or jquery ajax if possible?

后端 未结 4 1992
渐次进展
渐次进展 2021-01-06 07:28

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

相关标签:
4条回答
  • 2021-01-06 07:32

    If Ajax request does not interact with the UI, it doesn't really matters. $http is like Ajax request, the big difference is $http register to the digest cycle which update the UI with the new data. If there is no need in UI update, you can use whatever makes you happy.

    0 讨论(0)
  • 2021-01-06 07:36

    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.

    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.

    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

    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.

    0 讨论(0)
  • 2021-01-06 07:36

    You should use Angular infrastructure it's highly recommended. There's good introduction for jQuery developers to Angular http://www.ng-newsletter.com/posts/angular-for-the-jquery-developer.html

    There are discussions of difference between $http vs $.ajax Angularjs $http VS jquery $.ajax from jquery $.ajax to angular $http

    More over using jQuery with Angular can lead to some issues, e.g. https://github.com/angular/angular.js/issues/2548 (jQuery leads to incorrect work of ngClick with touch devices)

    0 讨论(0)
  • 2021-01-06 07:46

    I would personally recommend keeping it consistent with a common service layer that encapsulates http requests. While you can mix it up I only recommend doing that if you are dealing with code that has already been written with jquery. Also, if you end up wanting to change it later to update the UI, you would have to go back and change the jquery calls.

    Another point that was already made by Blaise is that $http really shines if you are doing unit testing and want to mock responses. Here is an example of this: http://www.unit-testing.net/CurrentArticle/How-to-mock-http-calls-in-Angular.html

    0 讨论(0)
提交回复
热议问题