在 AngularJS 中将服务转换为工厂
convert a service to a factory in AngularJS
我在angularjs里面写了下面的服务,how/what要不要改成工厂?另外,当使用工厂而不是服务时,advantages/differences 是什么?
angular.module('helloApp').service('popupService', function() {
var popup;
var setter = function(parameter) {
popup = parameter;
};
var getter = function() {
return popup;
};
return {
setter: setter,
getter: getter
};
});
提前致谢
要更改它,您首先应在模块中将其声明为工厂
angular.module('helloApp').factory('popupService', function() {
var popup;
var setter = function(parameter) {
popup = parameter;
};
var getter = function() {
return popup;
};
return {
setter: setter,
getter: getter
};
}
这个问题(工厂 VS 服务)是 Whosebug 中最受欢迎的问题之一:AngularJS: Service vs provider vs factory
Services
Syntax: module.service( 'serviceName', function );
Result: When
declaring serviceName as an injectable argument you will be provided
with an instance of the function. In other words new
FunctionYouPassedToService().
Factories
Syntax: module.factory( 'factoryName', function );
Result: When
declaring factoryName as an injectable argument you will be provided
with the value that is returned by invoking the function reference
passed to module.factory.
官方文档
您还可以在 Angular 网站上找到官方文档:
我在angularjs里面写了下面的服务,how/what要不要改成工厂?另外,当使用工厂而不是服务时,advantages/differences 是什么?
angular.module('helloApp').service('popupService', function() {
var popup;
var setter = function(parameter) {
popup = parameter;
};
var getter = function() {
return popup;
};
return {
setter: setter,
getter: getter
};
});
提前致谢
要更改它,您首先应在模块中将其声明为工厂
angular.module('helloApp').factory('popupService', function() {
var popup;
var setter = function(parameter) {
popup = parameter;
};
var getter = function() {
return popup;
};
return {
setter: setter,
getter: getter
};
}
这个问题(工厂 VS 服务)是 Whosebug 中最受欢迎的问题之一:AngularJS: Service vs provider vs factory
Services
Syntax: module.service( 'serviceName', function );
Result: When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService().
Factories
Syntax: module.factory( 'factoryName', function );
Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.
官方文档
您还可以在 Angular 网站上找到官方文档: