Angular $ http服务缓存无法正常工作

时间:2014-04-11 08:58:29

标签: javascript jquery angularjs

我在angular js中有一个$ http服务,它有一个缓存启用。第一次加载时,app服务会调用并获取缓存。现在,当我在同一页面的任何地方调用服务时,数据来自缓存,但是当我更改页面路由并再次从另一个页面调用服务时,数据来自服务器(我只是更改路由而不刷新页面)

编辑=> 代码正在运行!!在路由上,数据也来自缓存,但由于其他呼叫很少,因此需要更多时间。它花了更多的时间然后我接受缓存来响应。如果我从任何点击事件中调用相同的话,则需要2ms到3ms

这是我的服务

commonServicesModule.service('getDetails', ['$http', 'urlc',
    function($http, urlc) {

        return {
            consumer: {
                profile: function(id) {
                    return $http({
                        url: urlc.details.consumer.profile,
                        cache: true,
                        params: {
                            'consumer_id': id,
                            'hello': id,
                        },
                        method: 'GET',
                    }).success(function(result) {
                        return result;
                    });
                },

            }
        }
    }
])

来自控制器的呼叫:

start = new Date().getTime();
            /*get user information */
            getDetails.consumer.profile('1').then(function(results) {

                console.log('time taken for request form listCtrl ' + (new Date().getTime() - start) + 'ms');
            });

当我在路线之后从其他任何地方打电话时,它需要相同的时间。

1 个答案:

答案 0 :(得分:0)

尝试将consumer对象移动到函数体中,并返回对它的引用,如下所示:

commonServicesModule.service('getDetails', ['$http', 'urlc', function($http, urlc) {

    var getConsumer = {
        profile: function(id) {
            return $http({
                url: urlc.details.consumer.profile,
                cache: true,
                params: {
                    'consumer_id': id,
                    'hello': id,
                },
                method: 'GET',
            }).success(function(result) {
                return result;
            });
        }
    };

    return { consumer: getConsumer };

}]);