angularjs 中 Factory,Service,Provider 之间的区别
本片文章是使用了?angularjs 中使用 service 在controller 之間 share 對(duì)象和數(shù)據(jù)?的code(http://jsfiddle.net/kn46u0uj/1/) 來(lái)進(jìn)行演示?Factory,Service,Provider 之間的區(qū)別
?
1. Factory
factory('dataService',function(){return {golbal_sitename:"this is the shared value",sayHello:function(msg){alert(msg);}} })注意看上面的代碼,我們定義dataService 里面 ,后面的funciton 直接返回的是一個(gè)對(duì)象。 反回對(duì)象里面可以定義屬性和方法,上面就是返回了一個(gè)golbal_sitename屬性和sayHello方法。
簡(jiǎn)單點(diǎn)說(shuō)就是: 在factory 定義的function 返回的對(duì)象上面定義些屬性和方法, 等注入到controller后,就可以在controller調(diào)用這些屬性和方法了。
?
2. 我們來(lái)用service改寫(xiě)上面的代碼
service('dataService',function(){this.golbal_sitename = "this is the shared value";this.sayHello = function(msg){alert(msg);}; });注意上面的代碼和factory 定義的區(qū)別,這里我們?nèi)サ袅藃eturn 添加了this關(guān)鍵字。換句話說(shuō) factory 定義里面的function 其實(shí)是返回個(gè)對(duì)象,而service 定義里面的funciton 返回的是個(gè)類(lèi)定義。
也就是說(shuō)service 里面定義的dataService 最后是通過(guò)new 后面定義的function 來(lái)實(shí)例化的。
http://jsfiddle.net/kn46u0uj/3/
?
3. 使用Provider再次改寫(xiě)代碼
Provider 定義的 service 可以傳進(jìn) .config() 函數(shù)。當(dāng)我們需要在service 啟用前配置其模塊參數(shù)時(shí),就需要使用Provider來(lái)定義service.
代碼如下:
provider('dataService',function(){this.$get = function(){return {golbal_sitename:"this is the shared value",sayHello:function(msg){alert(msg);}}}; })http://jsfiddle.net/kn46u0uj/5/
?
上面使用三種方式定義的service 都可以正常工作, 唯一需要注意的就是使用當(dāng)service 需要傳入到config中進(jìn)行配置的時(shí)候,一定要使用provider進(jìn)行定義。
轉(zhuǎn)載于:https://www.cnblogs.com/slardar1978/p/4203979.html
總結(jié)
以上是生活随笔為你收集整理的angularjs 中 Factory,Service,Provider 之间的区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 深入理解C指针之四:指针和数组
- 下一篇: 效果