AngularJS中的非单一服务 [英] Non-Singleton Services in AngularJS
问题描述
AngularJS在其文档中明确指出服务是单例":
AngularJS clearly states in its documentation that Services are Singletons:
AngularJS services are singletons
与直觉相反,module.factory
还返回一个Singleton实例.
Counterintuitively, module.factory
also returns a Singleton instance.
鉴于非单例服务有很多用例,实现工厂方法以返回Service实例的最佳方法是什么,因此每次声明ExampleService
依赖项时,它都可以满足通过ExampleService
的另一个实例?
Given that there are plenty of use-cases for non-singleton services, what is the best way to implement the factory method to return instances of a Service, so that each time an ExampleService
dependency is declared, it is satisfied by a different instance of ExampleService
?
推荐答案
我认为我们不应该让工厂返回一个new
able函数,因为这会破坏依赖注入,并且库的行为会很尴尬,特别是对于第三方.简而言之,我不确定非单项服务是否有合法的用例.
I don't think we should ever have a factory return a new
able function as this begins to break down dependency injection and the library will behave awkwardly, especially for third parties. In short, I am not sure there are any legitimate use cases for non-singleton sevices.
完成同一件事的更好方法是使用工厂作为API,以返回带有附加的getter和setter方法的对象的集合.以下是一些伪代码,显示了使用这种服务的工作方式:
A better way to accomplish the same thing is to use the factory as an API to return a collection of objects with getter and setter methods attached to them. Here is some pseudo-code showing how using that kind of service might work:
.controller( 'MainCtrl', function ( $scope, widgetService ) {
$scope.onSearchFormSubmission = function () {
widgetService.findById( $scope.searchById ).then(function ( widget ) {
// this is a returned object, complete with all the getter/setters
$scope.widget = widget;
});
};
$scope.onWidgetSave = function () {
// this method persists the widget object
$scope.widget.$save();
};
});
这只是伪代码,用于通过ID查找小部件,然后能够保存对记录所做的更改.
This is just pseudo-code for looking up a widget by ID and then being able to save changes made to the record.
以下是该服务的一些伪代码:
Here's some pseudo-code for the service:
.factory( 'widgetService', function ( $http ) {
function Widget( json ) {
angular.extend( this, json );
}
Widget.prototype = {
$save: function () {
// TODO: strip irrelevant fields
var scrubbedObject = //...
return $http.put( '/widgets/'+this.id, scrubbedObject );
}
};
function getWidgetById ( id ) {
return $http( '/widgets/'+id ).then(function ( json ) {
return new Widget( json );
});
}
// the public widget API
return {
// ...
findById: getWidgetById
// ...
};
});
尽管未包含在此示例中,但这些灵活的服务也可以轻松管理状态.
Though not included in this example, these kinds of flexible services could also easily manage state.
我现在没有时间,但是如果有帮助的话,我可以稍后整理一个简单的Plunker进行演示.
I don't have time right now, but if it will be helpful I can put together a simple Plunker later to demonstrate.
这篇关于AngularJS中的非单一服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!