0
我目前正在試圖在我的角度應用程序中實現緩存服務,以減少終端上的工作負載並希望在我的界面上看到一些輕微的,可能忽略不計的加載時間。在AngularJS的工廠實現緩存
我已經實現我自己的cacheService
這是相當多的$cacheFactory
(function() {
'use strict';
angular
.module('app')
.factory('cacheService', cacheService);
cacheService.$inject = ['$cacheFactory']
function cacheService($cache) {
return $cache('appCache');
}
})();
然後包裝我有datacontext
基本上是消耗一個工作單元開始我cacheService
和$http
(我有幾個其他「資源庫」,在那裏,但只顯示了一個我試圖得到這個的合作伙伴)
(function() {
'use strict';
angular
.module('app')
.factory('datacontext', datacontext);
datacontext.$inject = ['$http', 'cacheService', '$q'];
function datacontext($http, cache, $q) {
var rulesRepo = (function() {
var repo = {
get: getRule,
getAll: getAll
};
return repo;
function getRule(ruleId) {
// placeholder
}
function getAll() {
var deferred = $q.defer();
// check to see if we have data cached
var rules = cache.get('rules');
if (rules) { // if it's cached, return it
deferred.resolve(rules);
} else { // otherwise get the data from the API, cache it and return it
$http.get('/api/rules')
.then(function (response) {
cache.put('rules', response.data);
deferred.resolve(response.data);
});
}
return deferred.promise;
}
})();
var service = {
rules: rulesRepo
};
return service;
}
})();
再消耗01我的角度控制器
(function() {
'use strict';
angular
.module('app')
.controller('HomeController', HomeController);
HomeController.$inject = ['$scope', 'datacontext'];
function HomeController($scope, context) {
context.rules.getAll()
.then(
function (data) { // success
$scope.rules = data;
},
function (response) { // failure
console.log(response);
});
activate();
function activate() { }
}
})();
我面對目前最大的問題是,每當我打這個電話給context.rules.getAll()
,它總是打else
說法,意思是rules
是不確定的,所以它絕不會使用緩存,它只是讓另一個調用我的API,獲取數據,緩存它(這部分工作,我已經通過在緩存中將緩存從緩存中拉出來進行測試),然後返回承諾。一遍又一遍。
有人可以指出我不明白這應該如何工作嗎?
因爲在角所有的工廠都是單身
這似乎是一個很好的解決方案,但更多的是解決方法,而不是我的問題的答案。 – 2014-11-04 17:53:57