angular.service vs angular.factory

后端 未结 9 2143
走了就别回头了
走了就别回头了 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:54

    app.factory('fn', fn) vs. app.service('fn',fn)

    Construction

    With factories, Angular will invoke the function to get the result. It is the result that is cached and injected.

     //factory
     var obj = fn();
     return obj;
    

    With services, Angular will invoke the constructor function by calling new. The constructed function is cached and injected.

      //service
      var obj = new fn();
      return obj;
    

    Implementation

    Factories typically return an object literal because the return value is what's injected into controllers, run blocks, directives, etc

      app.factory('fn', function(){
             var foo = 0;
             var bar = 0;
             function setFoo(val) {
                   foo = val;
             }
             function setBar (val){
                   bar = val;
             }
             return {
                    setFoo: setFoo,
                    serBar: setBar
             }
      });
    

    Service functions typically do not return anything. Instead, they perform initialization and expose functions. Functions can also reference 'this' since it was constructed using 'new'.

    app.service('fn', function () {
             var foo = 0;
             var bar = 0;
             this.setFoo = function (val) {
                   foo = val;
             }
             this.setBar = function (val){
                   bar = val;
             }
    });
    

    Conclusion

    When it comes to using factories or services they are both very similar. They are injected into a controllers, directives, run block, etc, and used in client code in pretty much the same way. They are also both singletons - meaning the same instance is shared between all places where the service/factory is injected.

    So which should you prefer? Either one - they are so similar that the differences are trivial. If you do choose one over the other, just be aware how they are constructed, so that you can implement them properly.

    0 讨论(0)
  • 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!";
          }
        }
      });
    
    0 讨论(0)
  • 2020-11-22 02:58

    Simply put ..

    const user = {
      firstName: 'john'
    };
    
    // Factory
    const addLastNameFactory = (user, lastName) => ({
      ...user,
      lastName,
    });
    
    console.log(addLastNameFactory(user, 'doe'));
    
    // Service
    const addLastNameService = (user, lastName) => {
      user.lastName = lastName; // BAD! Mutation
      return user;
    };
    
    console.log(addLastNameService(user, 'doe'));

    0 讨论(0)
  • 2020-11-22 02:59

    All the answers here seem to be around service and factory, and that's valid since that was what was being asked about. But it's also important to keep in mind that there are several others including provider(), value(), and constant().

    The key to remember is that each one is a special case of the other. Each special case down the chain allowing you to do the same thing with less code. Each one also having some additional limitation.

    To decide when to use which you just see which one allows you to do what you want in less code. Here is an image illustrating just how similar they are:

    For a complete step by step breakdown and quick reference of when to use each you can visit the blog post where I got this image from:

    http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

    0 讨论(0)
  • 2020-11-22 03:00

    I have spent some time trying to figure out the difference.

    And i think the factory function uses the module pattern and service function uses the standard java script constructor pattern.

    0 讨论(0)
  • 2020-11-22 03:03

    Here are the primary differences:

    Services

    Syntax: module.service( 'serviceName', function );

    Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service.

    Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending ( ) to the injected function reference. Could also be run with injectedArg.call( this ) or similar.

    Factories

    Syntax: module.factory( 'factoryName', function );

    Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

    Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.

    Here is example using services and factory. Read more about AngularJS Service vs Factory.

    You can also check the AngularJS documentation and similar question on stackoverflow confused about service vs factory.

    0 讨论(0)
提交回复
热议问题