新手角,使用服务I尝试加载cachefactory并使用控制器中的缓存。
这是服务方法
codesApp.service('CodeFilterService',function($filter, $http, CacheService,$log){
this.getByCodeType = function (codeTypeValue, codeName) {
if (angular.isUndefined(CacheService.get('Codes'))) {
loadCodes();
}
return $filter('filter')(CacheService.get('Codes'), {codetype: codeTypeValue, name: '!' + codeName});
};
this.getAllCodes = function () {
$log.info("getAllCodes");
if (angular.isUndefined(CacheService.get('Codes'))) {
$log.info("Loading fresh getAllCodes");
this.loadCodes();
}
return CacheService.get('Codes');
};
this.loadCodes = function () {
$http.get("./rest/codes").then(function (response) {
$log.info("Codes Size" +response.data.length );
CacheService.put('Codes', response.data);
});
};
});
codesApp.factory('CacheService',function($cacheFactory){
return $cacheFactory('super-cache');
});
控制器代码:
codesApp.controller('CodeCreateController',function($scope,$state,
Code,CodeFilterService,$log){
...
$scope.codeDropdownList = CodeFilterService.getAllCodes();
$log.info("codeDropdownList = " + angular.isUndefined($scope.codeDropdownList)) ;
});
此处angular.isUndefined($ scope.codeDropdownList))返回true,表示数据未加载。有没有办法解决这个问题。
答案 0 :(得分:0)
您可以使用承诺注入 $ q
codesApp.service('CodeFilterService', function ($filter, $http, CacheService, $log, $q) {
this.getByCodeType = function (codeTypeValue, codeName) {
if (angular.isUndefined(CacheService.get('Codes'))) {
loadCodes();
}
return $filter('filter')(CacheService.get('Codes'), {
codetype: codeTypeValue,
name: '!' + codeName
});
};
this.getAllCodes = function () {
$log.info("getAllCodes");
var deferred = $q.defer();
if (angular.isUndefined(CacheService.get('Codes'))) {
$log.info("Loading fresh getAllCodes");
this.loadCodes().then(function (result) {
$log.error('getAllCodes success');
var cachedCodes = CacheService.get('Codes');
deferred.resolve(cachedCodes);
}, function (reason) {
$log.error('getAllCodes error: ' + reason);
deferred.reject();
});
} else {
var cachedCodes = CacheService.get('Codes');
deferred.resolve(cachedCodes);
}
return deferred.promise;
};
this.loadCodes = function () {
$log.info("loadCodes");
var deferred = $q.defer();
$http.get("./rest/codes").then(function (response) {
$log.error('loadCodes success');
$log.info("Codes Size" + response.data.length);
CacheService.put('Codes', response.data);
deferred.resolve();
}, function (reason) {
$log.error('loadCodes error: ' + reason);
deferred.reject();
});
return deferred.promise;
};
});
codesApp.controller('CodeCreateController', function ($scope, $state,
Code, CodeFilterService, $log) {
...
CodeFilterService.getAllCodes().then(function (result) {
$log.info('result: ' + result);
$scope.codeDropdownList = result;
$log.info("codeDropdownList = " + angular.isUndefined($scope.codeDropdownList))
}, function (reason) {
$log.error('error: ' + reason);
});
});