3

I'm using anularJS in a project, I need a service in order to get JSONs with $http.get method, I think that a service would have an easier to read syntax:

app.service('ApiService' , function($http)
{
  var self = this;
  self.user = {};
  self.user.getByName = function(){};
  self.user.getByRate = function(){};

  self.events = {};

  self.events.getList = function(){};
  self.events.getByDate = function(){};

  return ({
    user : self.user,
    events : self.events
  });

});

and then you can call it like:

$scope.reople = ApiService.use.getList('some url');

but from too many pages (like this and this and this) I've seen, seem it's more popular to use factory as a better approach. can you please explain me:

  1. why is factory preferred and more popular than service?
  2. which is more extendable and maintainable for a group work or for a developer working on an existing code?
Community
  • 1
  • 1
Reyraa
  • 4,174
  • 2
  • 28
  • 54

2 Answers2

2

The .service() is just a derived version of .factory() and both are derived from .provider(), all of them are for registering services to use via DI across the app.

Please see AngularJS: Service vs provider vs factory if you would like to dive into detail.

The reason of why .factory() is popular probably because:

  • the .service() is too specific, you can only pass in a constructor function
  • the .provider() is too verbose, not all the time a service should be configurable

The .factory() is something in the middle that serve the needs of almost common usages.

app.factory('ApiService' , function($http) {
  function ApiService() {
    var self = this;
    self.user = {};
    self.user.getByName = function(){};
    self.user.getByRate = function(){};

    self.events = {};
    self.events.getList = function(){};
    self.events.getByDate = function(){};
  };

  return new ApiService();
});
Community
  • 1
  • 1
runTarm
  • 11,537
  • 1
  • 37
  • 37
2

factory is not preferred to service. based on the type of response you need it defers, do you need a callback or to return the value of results? respectively the suitable is service or factory.