我的 Angular js Web 应用程序中有以下代码片段。目的是在 Controller 中使用缓存以使应用程序更快。
我在 services.js 文件中定义了以下缓存工厂,该工厂将由我的应用程序中的多个 Controller 使用:
appServices.factory('AppCache', ['$cacheFactory', function($cacheFactory){
return $cacheFactory('app-cache');
}]);
现在我的一个 Controller 中有以下代码:
appControllers.controller('pageController', ['$scope', 'AppCache', 'AnotherService',
function pageController($scope, AppCache, AnotherService) {
$scope.init = function () {
if (angular.isUndefined(AppCache.get('d')))
{
AnotherService.get({},
function success(successResponse) {
$scope.data = successResponse.response.r;
AppCache.put('d', $scope.data);
},
function error(errorResponse) {
console.log("Error:" + JSON.stringify(errorResponse));
}
);
}
else
$scope.data = AppCache.get('d');
}
}
问题是我无法在缓存中保存或检索任何数据。当我使用上面的代码时,我的页面变成空白,因为没有检索到数据。
请帮助我理解我的错误。
最佳答案
您将缓存命名为 'app-cache'
,并尝试通过 'd'
访问它。在 Controller 中,只需将 'd'
替换为 'app-cache'
即可,它应该可以工作:
appControllers.controller('pageController', ['$scope', 'AppCache', 'AnotherService',
function pageController($scope, AppCache, AnotherService) {
$scope.init = function () {
if (angular.isUndefined(AppCache.get('app-cache')))
{
AnotherService.get({},
function success(successResponse) {
$scope.data = successResponse.response.r;
AppCache.put('app-cache', $scope.data);
},
function error(errorResponse) {
console.log("Error:" + JSON.stringify(errorResponse));
}
);
}
else
$scope.data = AppCache.get('app-cache');
}
关于javascript - 无法在 Angular JS 中正确使用缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34104689/