我的angular js网络应用程序中包含以下代码片段。目的是在控制器中使用缓存以使应用程序更快。

我在我的services.js文件中定义了以下缓存工厂,供我的应用程序中的多个控制器使用:

appServices.factory('AppCache', ['$cacheFactory', function($cacheFactory){
        return $cacheFactory('app-cache');
}]);


现在,我的一个控制器中具有以下代码:

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'访问它。在控制器中,只需将'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');
            }

07-28 02:42
查看更多