Service, Factory和Provider的不同 -- AngularJS

 References: 
  1. http://iffycan.blogspot.tw/2013/05/angular-service-or-factory.html
  2. http://docs.angularjs.org/guide/dev_guide.services.creating_services
  3. http://docs.angularjs.org/api/AUTO.$provide 
  4. http://docs.angularjs.org/api/angular.Module 
  5. http://stackoverflow.com/questions/15666048/angular-js-service-vs-provide-vs-factory
  6. http://docs.angularjs.org/guide/di

      在剛開始接觸AngularJS的service, factoryprovider(這三個是$provide提供的方法,請參考*3)很容易搞不清楚這三個的不同,而且官方網站也沒有說得很清楚。然後只好在網路上找了一些這三個有什麼樣不同的文章,然後紀錄整理出自己的想法,所以有任何錯誤歡迎告知 :) 

首先要講一下在AngularJs要註冊Services時有一下兩種方法:
範例我直接用官方的code,請參考*2

第一種使用angular.Module的api(參考*4)
  1. var myModule = angular.module('myModule', []);
  2. myModule.factory('serviceId', function() {
  3. var shinyNewServiceInstance;
  4. //factory function body that constructs shinyNewServiceInstance
  5. return shinyNewServiceInstance;
  6. });
第二種使用$provide service:
  1. angular.module('myModule', [], function($provide) {
  2. $provide.factory('serviceId', function() {
  3. var shinyNewServiceInstance;
  4. //factory function body that constructs shinyNewServiceInstance
  5. return shinyNewServiceInstance;
  6. });
  7. });
我以下的範例都會用angular.Module來說明Service, Factory和Provider的不同(*5):

P.S. 當定義好Service, Factory和Provider都是用Injection的方式來取的使用他們(*6)


1. Service
    module.service( 'serviceName', ServiceFunction );
    * Get service from 'new  ServiceFunction()'
2. Factory
    module.factory( 'factoryName', FactoryFunction );
    * Get factory from the value that is returned by invoking the FactoryFunction.
3. Provider
    module.provider( 'providerName', ProviderFunction);
    * Get provider from new ProviderFunction().$get()

以下是簡單的範例:

Check out this Pen!

<div ng-app='MyApp' ng-controller="MainCtrl">
  <div> {{FactoryName}} </div>
   <div> {{ServiceName}} </div>
   <div> {{ProviderName}} </div>
</div>
Check out this Pen!

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

function build(){
  this.name = "Factory"; 

  this.$get = function(){
    var self = this;
    self.name = "Provider";
    return self;
  }
  
  return this.name;
}

app.factory('ShowFactory', build);

app.provider("ShowProvider",build);

app.service('ShowService',build );

function MainCtrl($scope, ShowService, ShowFactory, ShowProvider){
   console.log(ShowFactory);
  $scope.FactoryName = ShowFactory; // 
  console.log(ShowService.name);
  $scope.ServiceName  = ShowService;  // create new
  $scope.ProviderName = ShowProvider; // pass by $get
}

Check out this Pen!
張貼留言

這個網誌中的熱門文章

Unions 在C語言的簡單介紹

解釋scope.$apply用來做什麼? -- AngularJS

JavaScript的Timer用法