angularjs - Non-Singleton Services in Angular -
angular states in documentation services singletons:
angular services singletons
counterintuitively, module.factory
returns singleton instance.
given there plenty of use-cases non-singleton services, best way implement factory method return instances of service, each time exampleservice
dependency declared, satisfied different instance of exampleservice
?
i don't think should ever have factory return new
able function begins break down dependency injection , library behave awkwardly, third parties. in short, not sure there legitimate use cases non-singleton sevices.
a better way accomplish same thing use factory api return collection of objects getter , setter methods attached them. here pseudo-code showing how using kind of service might work:
.controller( 'mainctrl', function ( $scope, widgetservice ) { $scope.onsearchformsubmission = function () { widgetservice.findbyid( $scope.searchbyid ).then(function ( widget ) { // returned object, complete getter/setters $scope.widget = widget; }); }; $scope.onwidgetsave = function () { // method persists widget object $scope.widget.$save(); }; });
this pseudo-code looking widget id , being able save changes made record.
here's pseudo-code 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 ); }); } // public widget api return { // ... findbyid: getwidgetbyid // ... }; });
though not included in example, these kinds of flexible services manage state.
i don't have time right now, if helpful can put simple plunker later demonstrate.
Comments
Post a Comment