All the documentation, examples and tutorials I've found on $resource were using it directly in the controller. So far I'm just using $http from services and those services are further used in the controllers. I thought $resource should replace $http and not my whole service. Is my thinking wrong, or were the examples I've found just so trivial that nobody bothered creating a service?

I've heard once the quote

When you want to create a command line interface for your application and you need to copy code out of the controller, than the controller has too much logic and it should be in a service.

Now, obviously this depends on the complexity of a controller, let's assume a simple CRUD view with the corresponding controller. It seems like $resource would be all I need and I can take it also to create a console application without caring about anything else from the controller. But something inside me is just shouting when I want to access the data ($resource) directly in the controller.

Where is the line to be drawn between when a service is necessary when it's overkill?

up vote 1 down vote accepted

This depends on the complexity and the long term goals of your app, but in my experience, your best bet is to wrap your $resource calls in a service since at some point in the future you'll find yourself pre/post processing the intput/output of your $resource calls and it's better to simply attach a new function (or parameter to an existing function) to the service that wraps your $resource calls rather than implement the processing code in every controller where you use the $resource. At first it may seem like it's pointless to add a wrapper that simply returns the $resource response immediately, but later on when the complexity grows, you'll be glad you did.

When you want to create a command line interface for your application and you need to copy code out of the controller, than the controller has too much logic and it should be in a service.

The reason this works is because your UI's are supposed to be independent of the service. A command line is a UI, and you shouldn't need a Controller to implement it, since you don't need Views, View Models or any of the other things that are part and parcel of an MVVM controller.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.