angular服務app
服務是對公共代碼的抽象,因爲依賴注入的要求,服務都是單例的,這樣咱們才能處處注入它們,而不用去管理它們的生命週期。
angular的服務有如下幾種類型:
常量(Constant): 用於聲明不會被修改的值。
變量(Value): 用於聲明會被修改的值。
服務(Service): 這個名稱跟服務這個大概念同名,就種行爲就像是給本身孩子取名爲"孩子"。只須要建立這個服務,而後等angular把它new出來,保存這個服務,而後就能夠處處注入了。
工廠(Factory): 它跟上面的Service不同,它不會被new出來。angular會調用這個函數,得到返回值,而後保存這個返回值,供它處處調用。
供應商(Provider): 在整個服務啓動以前,進行一些模塊化的配置。
看一張圖說明provider,服務等關係:ide
除了Constant以外,全部這些類型的服務,背後都是經過Provider實現的。最明顯的一個證實就是,當你使用未定義的服務時,angular給你的錯誤提示是它對應的Provider未找到。好比說使用了一個未定義的服務test,那麼錯誤提示是: Unknown provider:testProvider<- test。模塊化
Provider
provider必須有一個$get方法,聲明方式以下:函數
angular.module('myApp').provider('greeting', function(){ var name ='world'; this.setName = function(name){ name = name; }; this.$get = function(){ return 'hello, ' + name; } })
使用時:ui
angular.module('myApp').controller('someCtrl', function($scope, greeting){ $scope.message = greeting; }))
對這個Provider進行配置:this
angular.module('myApp').config(function(greetingProvider){ greetingProvider.setName('lyy'); })
注意,配置時要在名稱後加provider並遵循駝峯命名法,這樣angular才能正確注入該Provier。spa
Service
Service很適合在Controller中通訊或共享數據,Service裏能夠不用返回任何東西,由於angular會調用new關鍵字來建立對象。日誌
angular.module('myApp').service('greeting', function(){ this.sayHello = function(name){ return 'hello, ' + name; } })
使用:code
angular.module('myApp').controller('someCtrl', function($scope, greeting){ $scope.message = greeting.sayHello('world'); }))
至關於:對象
angular.module('myApp').provider('greeting', function(){ this.$get = function(){ var greeting = function(){ this.sayHello = function(name){ return 'hello, ' + name; } } return new greeting(); } })
Factory
Factory和Service的區別就是:factory是普通function,而service是一個構造器,因此factory能夠返回任何東西,而service能夠不返回。
angular.module('myApp').factory('greeting', function(){ return 'hello, world'; })
Constant
Constant比較特殊,它不是Provider的語法糖,並且它的初始化時機很是早,能夠在angular.module('myApp').config()中注入,而其餘的服務除了Provider以外都不能夠。這就意味着,若是你要在config中使用一個全局配置項,那麼它就只能聲明爲常量。Constant不能被裝飾器(decorator)裝飾。
angular.module('myApp').constant('name','lyy');
注入到config中:
angular.module('myApp').config(function(name){ $scope.userName=name; })
Value
Value與Constant的區別是,Value能夠被修改,不能注入到config中,可是能被裝飾器(decorator)裝飾。
angular.module('myApp').value('name','lyy');
angular提供了那麼多服務,那麼咱們應該何時用適合的服務呢?
若是是純數據,選Value;
若是還須要添加行爲,改寫成Service;
發現須要經過計算給出結果,改寫成Factory;
須要進行全局配置,改寫成Provider。
Decorator
Decorator比較特殊,它不是provider,它是用來裝飾其餘provider的。可是對於Decorator必定要慎用。
好比說有一個第三方庫叫ui,它有一個prompt函數,咱們不能改它的源碼,可是須要讓它每次彈出提問框時都在控制檯輸出一條記錄,那麼咱們能夠這樣寫:
angular.module('myApp').config(function($provide){ //$delegate是ui的原始服務 $provide.decorator('ui', function($delegate){ //保存原始的prompt函數 var originalPrompt=$delegate.prompt; //用本身的prompt代替 $delegate.prompt=function(){ //先執行原始的prompt函數 originalPrompt.apply($delegate, arguments); //寫一條日誌 console.log('prompt'); }; //返回原始服務的實例 return $delegate; }) })