Issue
I'm an AngularJS newbie, and I'm just starting to understand the concepts and differences of factory
, service
and controller
. As I understand, a factory
is used to return a "value object" that can be injected. Most examples I've seen do something like this:
angular.module('module.factories', function() {
factory('FactoryObject', function() {
return {
someFunction: function(someParam) {};
someOtherFunction: function(someOtherParam) {});
};
});
});
In my controller
, I want to be able to use this object, but I would like to initialize/instantiate it in the controller, since it can be re-initialized depending on events/actions in the controller. Therefore, I was wondering if I could return a constructor function in the factory instead?
angular.module('module.factories', function() {
factory('FactoryObject', function() {
function FactoryObject(initParam) {
}
FactoryObject.prototype.someFunction = function() {};
return FactoryObject;
});
});
Is this a suitable pattern for an angular factory? Or is it just "overkill" to use a factory for a custom object like this? Should I just include it in a library js file and reference it from there instead? One benefit of putting it in a factory is that it will be easy to mock it in a test since it will be injected where it's used. Are there any other mechanisms in Angular that could be used instead?
Solution
You're quite right, this is the way to create injectable "classes" (constructors). However, using factory
is only necessary when you need to inject other stuff to be used by your class:
.factory('Class', ['$q', function ($q) {
function Class () {}
Class.prototype = {
constructor: Class,
doSomeAsyncAction: function () {
return $q(function (resolve, reject) {
// ...
});
},
// ...
};
return Class;
})
If you're creating a completely independent class (e.g. some data structure), you can just use constant
, so that your class is available even in service providers:
(function (undefined) {
function Class () {}
Class.prototype = { ... };
angular.module(...)
.constant('Class', Class);
})();
As a sidenote, using provider
is not going to help you in this. Providers serve a completely different purpose and (among other things) return a factory function that is then used _once_ on the first requested injection to create a single instance of the service. Providers are used to let you configure that single service instance in the _config phase_ of application construction (see documentation).
Answered By - hon2a
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.