Call $http from controller

65 views
Skip to first unread message

Rajesh

unread,
Apr 28, 2014, 11:29:04 PM4/28/14
to ang...@googlegroups.com
Can I call a REST api using $http directly in my controller? When would I need to create my own service vs using $http service from controller? Most of the examples on the web just call $http in a custom service.

Yusuf Alii

unread,
Apr 28, 2014, 11:45:21 PM4/28/14
to ang...@googlegroups.com
As a rule of thumb, if you want to re-use your  functionality in different controllers then you should create it as a service instead of hard coding in one controller.

This would minimize code redundancy and make your app more modular.

Gordon Bockus

unread,
Apr 29, 2014, 1:13:19 AM4/29/14
to ang...@googlegroups.com
The thing that you will run into is if you make http calls from your controller then it is more painful to write unit tests.  If you use a service there is a lot less overhead in mocking that service response then in spying on $http.  

Rajesh

unread,
Apr 29, 2014, 3:40:36 AM4/29/14
to ang...@googlegroups.com
Gordon, Yusuf,

Thanks for your responses. The only thing that the services are required to do is a simple http get / post. All business logic / validation is done on the server. Are there any advantages by using a custom service in this scenario?

- Rajesh

On Tuesday, April 29, 2014 8:59:04 AM UTC+5:30, Rajesh wrote:

Aaron Siladi

unread,
Apr 30, 2014, 1:27:10 AM4/30/14
to ang...@googlegroups.com
The Angular way would be to create a service which returns a $resource.

$resource a higher level abstraction on $http for REST interfaces
https://docs.angularjs.org/api/ngResource/service/$resource

As mentioned by others the benefit are the following:
1.  You can reuse it in many controllers
2.  More ease of unit testing

Rajesh Elumalai

unread,
May 2, 2014, 3:31:50 AM5/2/14
to ang...@googlegroups.com
Thanks Aaron! That was helpful.


--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/dJ6xfEk93s0/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.



--
Regards,
Rajesh
Reply all
Reply to author
Forward
0 new messages