angularjs中provider,factory,service的區別和用法
provider->factory->service
都能提供service,但是又有差別
service
第一次被注入時實例化,只實例化一次,整個應用的生命周期中是個單例模式,可以用來在controller之間傳遞數據
//使用new關鍵字實例化,所以直接使用this定義service
//不知道為啥就看看js中的this怎么玩的
.service('myService', ['', function() {
this.getName = function() {
return 'CooMark';
}
}])
factory
//返回一個對象,可能這是你喜歡的方式,使用call的方式實例化,其他的和service一樣
//Internally this is a short hand for $provide.provider(name, {$get: $getFn}).
angular.module('app', [])
.factory('myFactory', ['', function() {
return {
getName: function() {
return 'CooMark';
},
getTitle: function() {
return 'Engineer'
}
}
}])
provider
這是唯一能注入到config的service,這樣定義的service在你開始注入之前就已經實例化,開發共享的模塊的時候常常使用它,能夠在使用之前進行配置,比如你可能需要配置你的服務端的url
//兩種形式的參數,都是為了得到一個帶有$get屬性的對象
// Object: then it should have a $get method. The $get method will be invoked using $injector.invoke() when an instance needs to be created.
// Constructor: a new instance of the provider will be created using $injector.instantiate(), then treated as object.
angular.module('app', [])
.config(['$provider', function() {
$provider.provider('myProvider', function() {
this.$get = function() {
return {
getName: function() {
return 'CooMark';
}
}
}
});
$provider.provider('myProvider', {
$get: function() {
return {
getName: function() {
return 'CooMark';
}
}
}
});
}])

參考:
https://docs.angularjs.org/api/auto/service/$provide
http://www.cnblogs.com/joyco773/p/5702337.html
http://www.360doc.com/content/16/0728/14/22900036_579091190.shtml
https://my.oschina.net/tanweijie/blog/295067
