I have seen both angular.factory() and angular.service() used to declare services; however, I cannot find angular.service
anywhere in official documentation.
Services and factories are similar to one another. Both will yield a singleton object that can be injected into other objects, and so are often used interchangeably.
They are intended to be used semantically to implement different design patterns.
A service pattern is one in which your application is broken into logically consistent units of functionality. An example might be an API accessor, or a set of business logic.
This is especially important in Angular because Angular models are typically just JSON objects pulled from a server, and so we need somewhere to put our business logic.
Here is a Github service for example. It knows how to talk to Github. It knows about urls and methods. We can inject it into a controller, and it will generate and return a promise.
(function() {
var base = "https://api.github.com";
angular.module('github', [])
.service('githubService', function( $http ) {
this.getEvents: function() {
var url = [
base,
'/events',
'?callback=JSON_CALLBACK'
].join('');
return $http.jsonp(url);
}
});
)();
Factories, on the other hand are intended to implement a factory pattern. A factory pattern in one in which we use a factory function to generate an object. Typically we might use this for building models. Here is a factory which returns an Author constructor:
angular.module('user', [])
.factory('User', function($resource) {
var url = 'http://simple-api.herokuapp.com/api/v1/authors/:id'
return $resource(url);
})
We would make use of this like so:
angular.module('app', ['user'])
.controller('authorController', function($scope, User) {
$scope.user = new User();
})
Note that factories also return singletons.
Because a factory simply returns an object, it can return any type of object you like, including a constructor function, as we see above.
Another technical difference is in the way services and factories are composed. A service function will be newed to generate the object. A factory function will be called and will return the object.
This means that in a service, we append to "this" which, in the context of a constructor, will point to the object under construction.
To illustrate this, here is the same simple object created using a service and a factory:
angular.module('app', [])
.service('helloService', function() {
this.sayHello = function() {
return "Hello!";
}
})
.factory('helloFactory', function() {
return {
sayHello: function() {
return "Hello!";
}
}
});