The service
method provides the capability to implement functionality into a server. However, the service
method works slightly differently than the factory
method. The service
method accepts a constructor function as the second argument and uses it to create a new instance of an object. The service
method uses the following syntax, where name
is the service name and constructor
is a constructor function:
service(name, constructor)
The service
method can also accept dependency injection. The following code implements a basic service method that provides an add()
function and a multiply()
function:
var app = angular.module('myApp', []);
app.constant('myConst', 10);
function ConstMathObj(myConst) {
this.add = function(value){ return value + myConst; };
this.multiply = function(value){ return value * myConst; };
}
app.service('constMath', ['myConst', ConstMathObj] );
Notice that the ConstMathObj
constructor is created first, and then the service()
method calls it and uses dependency injection to insert the myConst
service.