Skip to content Skip to sidebar Skip to footer

Should I Use Angularjs $http Service For Requests Or Jquery Ajax If Possible?

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

Solution 1:

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.


Solution 2:

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


Solution 3:

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.


Solution 4:

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)


Post a Comment for "Should I Use Angularjs $http Service For Requests Or Jquery Ajax If Possible?"