Recently some co-workers and I were having a discussion as to whether or not AngularJS services should have state or not. We came up with some arguments for and against it a
In AngularJS, services are passed in via factory function. And basically they are objects that can contain some state (e.g. for caching or storing data needed for performing their actions).
One good solution that can take both cons of having/not having state is when service (that could be actually function) that return object that contain state.
Take a look at the $http
service: you can get instance of this service calling
var x = $http({url:'...'});
And then call by
var result = x.get() //actually `$http.get` is shortcut of this operation
Same with ngResource
: using service you get object with some state that can perform desired actions.
So basically I think that is the best option: from one point you avoid 'side effects' by moving state that could be modified by actions into separate object, not stored in service itself, but can have specific state in that object to be able to store custom info (like auth information etc).