Confused about Service vs Factory

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

    Adding to the first answer, I think .service() is for people who have written their code in more object oriented style(C#/Java) (using this keyword and instantiating object via prototype/Constructor function).

    Factory is for developers who write code which is more natural to javascript/functional style of coding.

    Take a look at the source code of .service and .factory method inside angular.js - internally they all call provider method:

      function provider(name, provider_) {
        if (isFunction(provider_)) {
          provider_ = providerInjector.instantiate(provider_);
        }
        if (!provider_.$get) {
          throw Error('Provider ' + name + ' must define $get factory method.');
        }
        return providerCache[name + providerSuffix] = provider_;
      }
    
      function factory(name, factoryFn) { \
        return provider(name, { $get: factoryFn }); 
      }
    
      function service(name, constructor) {
        return factory(name, ['$injector', function($injector) {
          return $injector.instantiate(constructor);
        }]);
      }
    

提交回复
热议问题