Confused about Service vs Factory

后端 未结 20 2398
轻奢々
轻奢々 2020-11-22 08:49

As I understand it, when inside a factory I return an object that gets injected into a controller. When inside a service I am dealing with the object using this

20条回答
  •  有刺的猬
    2020-11-22 09:20

    All angular services are singletons:

    Docs (see Services as singletons): https://docs.angularjs.org/guide/services

    Lastly, it is important to realize that all Angular services are application singletons. This means that there is only one instance of a given service per injector.

    Basically the difference between the service and factory is as follows:

    app.service('myService', function() {
    
      // service is just a constructor function
      // that will be called with 'new'
    
      this.sayHello = function(name) {
         return "Hi " + name + "!";
      };
    });
    
    app.factory('myFactory', function() {
    
      // factory returns an object
      // you can run some code before
    
      return {
        sayHello : function(name) {
          return "Hi " + name + "!";
        }
      }
    });
    

    Check out this presentation about $provide: http://slides.wesalvaro.com/20121113/#/

    Those slides were used in one of the AngularJs meetups: http://blog.angularjs.org/2012/11/more-angularjs-meetup-videos.html

提交回复
热议问题