Confused about Service vs Factory

后端 未结 20 2769
轻奢々
轻奢々 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:17

    I had this confusion for a while and I'm trying my best to provide a simple explanation here. Hope this will help!

    angular .factory and angular .service both are used to initialize a service and work in the same way.

    The only difference is, how you want to initialize your service.

    Both are Singletons


    var app = angular.module('app', []);
    


    Factory

    app.factory(, )

    If you would like to initialize your service from a function that you have with a return value, you have to use this factory method.

    e.g.

    function myService() {
      //return what you want
      var service = {
        myfunc: function (param) { /* do stuff */ }
      }
      return service;
    }
    
    app.factory('myService', myService);
    

    When injecting this service (e.g. to your controller):

    • Angular will call your given function (as myService()) to return the object
    • Singleton - called only once, stored, and pass the same object.


    Service

    app.service(, )

    If you would like to initialize your service from a constructor function (using this keyword), you have to use this service method.

    e.g.

    function myService() {
      this.myfunc: function (param) { /* do stuff */ }
    }
    
    app.service('myService', myService);
    

    When injecting this service (e.g. to your controller):

    • Angular will newing your given function (as new myService()) to return the object
    • Singleton - called only once, stored, and pass the same object.


    NOTE: If you use factory with or service with , it will not work.


    Examples - DEMOs

    • Angular Service vs Factory
    • Angular Service vs Factory (with route)

提交回复
热议问题