摘要:AngularJS 的 Module 提供了三個方法(method)來定義你的 Service:Service/Factory/Provider
angularJS for Factory.zipangularJS for Provider.zip線上編輯angularJS:http://plnkr.co/edit/dxL3n00ZLBEzCWA4S8ms?p=preview
1:====Factory 方法,你必須提供一個工廠方法,並自己建立一個 Service Object================
var demoApp = angular.module("demoApp", []);
demoApp.factory("echoService", function(){
var echoCount = 0;
//回傳物件
return {
echo: function(name){
return console.log((echoCount++) + ", Your name is " + name);
}
};
});
2:====Service 方法,你必須提供一個建構子,由 AngularJS 幫你建立 Service Object===========
var demoApp = angular.module("demoApp", []);
demoApp.service("echoService", function(){
this.echoCount = 0;
//建構子
this.echo = function(name){
return console.log((this.echoCount++) + ", Your name is " + name);
};
})
>>上述黃色框裡Service裡另一種簡易寫法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
var echoService = function(){
this.echoCount = 0;
this.echo = function(name){
return console.log((this.echoCount++) + ", Your name is " + name);
};
};
>>>Service 相等 Factory相同寫法>>>>>>>>>>完完全全可以把 factory method 的範例直接換成用 service method>>>>>>>>>>>>>>>>>>>>>>
demoApp.factory("echoService", function(){
console.log("Factory Function be executed...");
var echoCount = 0;
return {
echo: function(name){
return console.log((echoCount++) + ", Your name is " + name);
}
};
});
demoApp.service("echoService", function(){
console.log("Factory Function be executed...");
var echoCount = 0;
return {
echo: function(name){
return console.log((echoCount++) + ", Your name is " + name);
}
};
});
3:==Provider Object 必須包含一個 $get的函式====================================================================
======provider 方法能夠讓我們增加額外的函式來設定 Service Objec
demoApp.provider("echoService", function(){
var enableEcho = true;
return { //It's Provider Object
echoFunctionEnabled: function(enabled){
enableEcho = enabled;
},
$get: function(){
return { //It's Service Object
echoCount: 0,
echo: function(name){
if(enableEcho){
console.log((this.echoCount++) + ", Your name is " + name);
}else {
console.log("Echo function disabled.");
}
}
};
}
}
});
=====適當時機點呼叫 Provider Object 的 echoFunctionEnabled 函式呢??====onfig 會在 AngularJS 把所有的模組載入之後才會執行==
demoApp.config(function (echoServiceProvider) {
echoServiceProvider.echoFunctionEnabled(false);
});
REF:http://programer-learn.blogspot.tw/2014/07/angularjs-service.html
這三個方法的結果完全是一樣的,就是一個 Service Object (注意:是一個物件)
而這三種方法的差別其實僅在於 Service Object 的建立與管理的過程