Angular在其文档中清楚地说明服务是单例:
- Angular services are singletons
反直觉,module.factory也返回一个Singleton实例。
考虑到非单例服务有很多用例,什么是实现工厂方法来返回一个服务的实例的最好方法,这样每次声明一个ExampleService依赖项时,它被一个不同的实例ExampleService?
我不认为我们应该有一个工厂返回一个可更新的函数,因为这开始打破依赖注入和库将表现得尴尬,特别是对于第三方。总之,我不确定有没有任何合法用例非单身服务。
一个更好的方法来完成同样的事情是使用工厂作为一个API返回一个对象的集合,并附加了getter和setter方法。这里是一些伪代码显示如何使用这种服务可能工作:
- .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查找窗口小部件,然后能够保存对记录所做更改的伪代码。
这里有一些服务的伪代码:
- .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
- // ...
- };
- });
虽然没有包括在这个例子中,这些灵活的服务也可以轻松地管理状态。
我现在没有时间,但如果它会有所帮助,我可以把一个简单的Plunker稍后展示。