【问题标题】:Angular $http service cache not working properlyAngular $http 服务缓存无法正常工作
【发布时间】:2014-04-11 08:58:29
【问题描述】:

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

编辑 => 代码工作!在路由上,数据也来自缓存,但由于其他调用很少,因此需要更多时间。只是花了更多时间然后我接受了缓存来响应。如果我从任何点击事件中调用相同的,那么它将需要 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');
            });

当我在路由后从其他任何地方调用它时,它需要相同的时间。

【问题讨论】:

  • 尝试从返回中拉出你的“消费者”对象,将它向上移动到函数体中,然后在返回中引用它而不是在那里定义它。
  • @marck .. 不明白你能把代码放上去吗?

标签: javascript jquery angularjs


【解决方案1】:

尝试将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 };

}]);

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    相关资源
    最近更新 更多