What is Non-Singleton Services in AngularJS?

What is Non-Singleton Services in AngularJS?

Asked on October 23, 2018 in AngularJs.
Add Comment


  • 7 Answer(s)

       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();
      };
    });
    

      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
        // ...
      };
    });
    
    Answered on October 23, 2018.
    Add Comment

        A factory return instances of an object. You should be able to modify this to suit your needs.

    var ExampleApplication = angular.module('ExampleApplication', []);
    ExampleApplication.factory('InstancedService', function(){
    function Instance(name, type)
    {
      this.name = name;
      this.type = type;
    }
    return
    {
      Instance: Instance
    }
    });
    
    ExampleApplication.controller('InstanceController', function($scope, InstancedService){
      var instanceA = new InstancedService.Instance('A','string'),
        instanceB = new InstancedService.Instance('B','object');
      console.log(angular.equals(instanceA, instanceB));
    });
    

    JsFiddle

    Updated

       Consider the following request for non-singleton services.

       The idea that all services are singletons does not stop you from writing singleton factories that can instantiate new objects.

       and his example of returning instances from factories:

    myApp.factory('myService', function ()
    {
      var MyThing = function () {};
      MyThing.prototype.foo = function () {};
      return
    {
        getInstance: function ()
    {
          return new MyThing();
        }
      };
    });
    

      I would also argue his example is superior due to the fact that you do not have to use the new keyword in your controller. It is encapsulated within the getInstance method of the service.

    Answered on October 23, 2018.
    Add Comment

    Another way is to copy service object with angular.extend().

    app.factory('Person', function()
    {
      return
    {
        greet: function() { return "Hello, I'm " + this.name; },
        copy: function(name) { return angular.extend({name: name}, this); }
      };
    });
    

    and then, for example, in our controller

    app.controller('MainCtrl', function ($scope, Person)
    {
      michael = Person.copy('Michael');
      peter = Person.copy('Peter');
      michael.greet(); // Hello I'm Michael
      peter.greet(); // Hello I'm Peter
    });
    
    Answered on October 23, 2018.
    Add Comment

    This is an  of simple example of Non-Singleton services in AngularJS accessing with objects using rootscope:

    var App = angular.module('App', []);
    App.counter = 0;
    function MyObject($rootScope) {
      this.$rootScope = $rootScope;
      this.name = "MyObject " + App.counter++;
    }
    MyObject.prototype.getText = function () {
      return this.name;
    };
    App.factory('MyObject', function ($injector) {
      return function() { return $injector.instantiate(MyObject); };
    });
    function MyObjectWithParam($rootScope, name) {  
      this.$rootScope = $rootScope;
      this.name = name;
    }
    MyObjectWithParam.prototype.getText = function () {
      return this.name;
    };
    App.factory('MyObjectWithParam', function ($injector) {
      return function(name) { return $injector.instantiate(MyObjectWithParam, { name: name }); };
    });
    function MyCtrl($scope, MyObject, MyObjectWithParam) {
      var obj1 = new MyObject(),
      swa = new MyObject(),
      obj2 = new MyObjectWithParam("hello"),
      obj3 = new MyObjectWithParam("world");
    $scope.text = [swa.getText(),
      obj1.getText(),
      obj2.getText(),
      obj3.getText()];
    }
    
    Answered on December 15, 2018.
    Add Comment

    Using the Component provider method, like since sole purpose of the service is to share data between child’s components and to provide a couple of helper’s methods.So, we stick it in the component providers and make it a non-singleton service.

    
    @Component({
    
    selector: 'admin-tab',
    
    providers: [AdminService, AdminDataService]
    
    })
    
    
    Answered on December 15, 2018.
    Add Comment

    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();
      };
    });

    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
        // ...
      };
    });
    Answered on February 14, 2019.
    Add Comment

    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();
      };
    });
    Answered on February 22, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.