angular.service vs angular.factory

后端 未结 9 2255
走了就别回头了
走了就别回头了 2020-11-22 02:50

I have seen both angular.factory() and angular.service() used to declare services; however, I cannot find angular.service anywhere in official documentation.

9条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 02:57

    The clue is in the name

    Services and factories are similar to one another. Both will yield a singleton object that can be injected into other objects, and so are often used interchangeably.

    They are intended to be used semantically to implement different design patterns.

    Services are for implementing a service pattern

    A service pattern is one in which your application is broken into logically consistent units of functionality. An example might be an API accessor, or a set of business logic.

    This is especially important in Angular because Angular models are typically just JSON objects pulled from a server, and so we need somewhere to put our business logic.

    Here is a Github service for example. It knows how to talk to Github. It knows about urls and methods. We can inject it into a controller, and it will generate and return a promise.

    (function() {
      var base = "https://api.github.com";
    
      angular.module('github', [])
        .service('githubService', function( $http ) {
          this.getEvents: function() {
            var url = [
              base,
              '/events',
              '?callback=JSON_CALLBACK'
            ].join('');
            return $http.jsonp(url);
          }
        });
      )();
    

    Factories implement a factory pattern

    Factories, on the other hand are intended to implement a factory pattern. A factory pattern in one in which we use a factory function to generate an object. Typically we might use this for building models. Here is a factory which returns an Author constructor:

    angular.module('user', [])
      .factory('User', function($resource) {
        var url = 'http://simple-api.herokuapp.com/api/v1/authors/:id'
        return $resource(url);
      })
    

    We would make use of this like so:

    angular.module('app', ['user'])
      .controller('authorController', function($scope, User) {
        $scope.user = new User();
      })
    

    Note that factories also return singletons.

    Factories can return a constructor

    Because a factory simply returns an object, it can return any type of object you like, including a constructor function, as we see above.

    Factories return an object; services are newable

    Another technical difference is in the way services and factories are composed. A service function will be newed to generate the object. A factory function will be called and will return the object.

    • Services are newable constructors.
    • Factories are simply called and return an object.

    This means that in a service, we append to "this" which, in the context of a constructor, will point to the object under construction.

    To illustrate this, here is the same simple object created using a service and a factory:

    angular.module('app', [])
      .service('helloService', function() {
        this.sayHello = function() {
          return "Hello!";
        }
      })
      .factory('helloFactory', function() {
        return {
          sayHello: function() {
            return "Hello!";
          }
        }
      });
    

提交回复
热议问题