When you're in the process of creating an Angular service or factory, it's interesting to note that Angular ultimately utilizes the same function for both cases:
function factory(name, factoryFn, enforce) {
return provider(name, {
$get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
});
}
For a service, typically there isn't a return value involved, and behind the scenes, Object.create()
is employed to generate an object containing the sayHello
method.
app.service('MyService', function () {
this.sayHello = function () {
console.log('hello');
};
});
In contrast, with a factory, an object literal is returned instead:
app.factory('MyService', function () {
return {
sayHello: function () {
console.log('hello');
};
}
});
The use of enforce is primarily to ensure a return value. It's not solely about deciding between "service or factory," as even from a service, you can still return an object literal if desired:
app.service('MyService', function () {
return {
sayHello: function () {
console.log('hello');
};
}
});
As for the dilemma of "Which one should you choose?" feel free to explore this resource for further insights: