【发布时间】:2016-04-29 04:51:46
【问题描述】:
新手到角度,使用服务我正在尝试加载缓存工厂并使用来自控制器的缓存。
这里是服务方法
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,这意味着数据没有被加载。有什么办法可以解决这个问题。
【问题讨论】:
-
问题很简单... ajax 是异步的,所以你不能调用
loadcodes()并立即返回控制器。可能希望在控制器运行之前使用路由器中的解析来加载缓存 -
@charlietfl 谢谢,你能提供答案或psedocode
标签: angularjs angularjs-service angularjs-http