[英]Using service as Model
我希望此服務表現為模型。
angular.module('secrunApp').service('appState', function () {
this.currentAnswerset = 1;
this.currentQuestion = 2;
this.name;
function set(key, value) {
console.log('>> set appStateModel', key, value);
var localVar = key;
this[localVar] = value;
}
function get(key) {
console.log('<< get appStateModel', key, this[key]);
return this[key];
}
return {
get: get,
set: set
}
});
幾個問題。
1 - 最初在啟動應用程序和訪問此道具時未定義默認屬性。 為什么會這樣?
2 - 這是一個簡單但正確的將服務作為模型處理並存儲可在整個應用程序中訪問的數據嗎?
3 - 我假設只返回一個get / set API,其余的屬性不能直接訪問(類似私有),但它們不是。 有人可以解釋為什么會這樣嗎?
一旦注入控制器,我設置並獲得如下屬性值,完美地工作。
appState.set('name', 'SJV');
appState.get('name');
一般問題:什么是一個可靠和正確的實施。 我想保持簡單,平易近人。
此引用是指您的服務創建功能,而不是您要返回的對象。 這是一個修復示例。
var result = {};
result.currentAnswerset = 1;
result.currentQuestion = 2;
result.name;
function set(key, value) {
console.log('>> set appStateModel', key, value);
var localVar = key;
result[localVar] = value;
}
function get(key) {
console.log('<< get appStateModel', key, result[key]);
return result[key];
}
result.get = get;
result.set = set;
return result;
問題1
.service()
需要一個構造函數。 哪個Angular使用new
運算符實例化。 因此,您不需要返回新對象。 JavaScript為您返回對象。 現在,在服務構造函數中,您可以將public函數添加this
變量中。
angular .module('secrunApp') .service('appState', function () { this.currentAnswerset = 1; this.currentQuestion = 2; this.name; this.set = function (key, value) { console.log('>> set appStateModel', key, value); var localVar = key; this[localVar] = value; }; this.get = function (key) { console.log('<< get appStateModel', key, this[key]); return this[key]; }; });
現在,你的服務實例的引用由提到相同的對象this
服務構造函數中。 但由於您的數據與服務對象本身相關聯,因此它們不是私有的。 我們稍后回過頭來。
問題2
您可以嘗試在DOM中使用更高的基本控制器,以處理所有應用級視圖模型。 例如
<body ng-controller="AppController as appVm"> <div ng-controller="SomethingController as somethingVm"> <p>{{ appVm.currentAnswerset }}</p> </div> </body>
問題3
要保持變量私有,請在服務構造函數中定義一個局部變量,只有getter和setter才能通過閉包訪問。
angular .module('secrunApp') .service('appState', function () { // Private data only getter and setter can access var data = { currentAnswerset: 1, currentQuestion: 2, name: '' }; this.set = function (key, value) { data[key] = value; }; this.get = function (key) { return data[key]; }; });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.