我希望能够创建一个自定义AngularJS服务,当它的数据对象为空时,它会发出一个HTTP“Get”请求,并在成功时填充数据对象。
下次调用此服务时,我希望绕过再次发出HTTP请求的开销,而是返回缓存的数据对象。
这可能吗?
我希望能够创建一个自定义AngularJS服务,当它的数据对象为空时,它会发出一个HTTP“Get”请求,并在成功时填充数据对象。
下次调用此服务时,我希望绕过再次发出HTTP请求的开销,而是返回缓存的数据对象。
这可能吗?
当前回答
如果你喜欢$http的内置缓存,但想要更多的控制,请查看angular-cache库。您可以使用它来无缝地增加$http缓存,包括生存时间(time-to-live)、定期清除以及将缓存持久化到localStorage的选项,以便跨会话可用。
FWIW,它还提供了一些工具和模式,使您的缓存成为一种更动态的数据存储,您可以将其作为POJO进行交互,而不仅仅是默认的JSON字符串。目前还不能评论这个选项的效用。
(然后,在此基础上,相关库angular-data在某种程度上替代了$resource和/或Restangular,并依赖于angular-cache。)
其他回答
在当前的稳定版本(1.0.6)中,一种更简单的方法需要更少的代码。
设置好模块后,添加一个工厂:
var app = angular.module('myApp', []);
// Configure routes and controllers and views associated with them.
app.config(function ($routeProvider) {
// route setups
});
app.factory('MyCache', function ($cacheFactory) {
return $cacheFactory('myCache');
});
现在你可以把它传递到你的控制器:
app.controller('MyController', function ($scope, $http, MyCache) {
$http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) {
// stuff with results
});
});
一个缺点是键名也是自动设置的,这可能会使清除它们变得棘手。希望他们能以某种方式添加键名。
Angular的$http有一个内置的缓存。根据文件:
cache - {boolean|Object} -使用$cacheFactory创建的布尔值或对象,用于启用或禁用HTTP响应的缓存。看到 $http缓存 信息。
布尔值
所以你可以在它的选项中将cache设置为true:
$http.get(url, { cache: true}).success(...);
或者,如果你喜欢配置类型的呼叫:
$http({ cache: true, url: url, method: 'GET'}).success(...);
缓存对象
你也可以使用缓存工厂:
var cache = $cacheFactory('myCache');
$http.get(url, { cache: cache })
你可以自己使用$cacheFactory来实现它(特别是在使用$resource时):
var cache = $cacheFactory('myCache');
var data = cache.get(someKey);
if (!data) {
$http.get(url).success(function(result) {
data = result;
cache.put(someKey, data);
});
}
angularBlogServices.factory('BlogPost', ['$resource',
function($resource) {
return $resource("./Post/:id", {}, {
get: {method: 'GET', cache: true, isArray: false},
save: {method: 'POST', cache: false, isArray: false},
update: {method: 'PUT', cache: false, isArray: false},
delete: {method: 'DELETE', cache: false, isArray: false}
});
}]);
将cache设置为true。
如果你喜欢$http的内置缓存,但想要更多的控制,请查看angular-cache库。您可以使用它来无缝地增加$http缓存,包括生存时间(time-to-live)、定期清除以及将缓存持久化到localStorage的选项,以便跨会话可用。
FWIW,它还提供了一些工具和模式,使您的缓存成为一种更动态的数据存储,您可以将其作为POJO进行交互,而不仅仅是默认的JSON字符串。目前还不能评论这个选项的效用。
(然后,在此基础上,相关库angular-data在某种程度上替代了$resource和/或Restangular,并依赖于angular-cache。)
我想现在有一个更简单的方法。这将为所有$http请求($resource继承的)启用基本缓存:
var app = angular.module('myApp',[])
.config(['$httpProvider', function ($httpProvider) {
// enable http caching
$httpProvider.defaults.cache = true;
}])