angular.service vs angular.factory

后端 未结 9 2260
走了就别回头了
走了就别回头了 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.

提交回复
热议问题