javascript - 无法在 Angular JS 中正确使用缓存

标签 javascript angularjs angularjs-directive angularjs-scope

我的 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/

相关文章:

javascript - ngOptions 按值比较

javascript - 以数字开头的类或方法名称,为什么不呢?

javascript - 如果我不知道变量的类型(可能是数组、对象或基元),如何从变量中清除以前的数据

javascript - Angular 模型未更新

javascript - Angular - ngChange 在 <select> 的 ngModel 之前触发

angularjs - 更新缓存的模板

javascript - 序列化表单以便通过 Ajax 发送它

javascript - 如何在 AngularJS 中初始化嵌套 Controller ?

angularjs - 如何获取 angularjs 范围 id

javascript - 如果人们建议我不应该使用 .innerHTML,那么我应该改用什么?