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
?
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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With