我希望能够创建一个自定义AngularJS服务,当它的数据对象为空时,它会发出一个HTTP“Get”请求,并在成功时填充数据对象。
下次调用此服务时,我希望绕过再次发出HTTP请求的开销,而是返回缓存的数据对象。
这可能吗?
我希望能够创建一个自定义AngularJS服务,当它的数据对象为空时,它会发出一个HTTP“Get”请求,并在成功时填充数据对象。
下次调用此服务时,我希望绕过再次发出HTTP请求的开销,而是返回缓存的数据对象。
这可能吗?
当前回答
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。
其他回答
由于AngularJS的工厂是单例的,你可以简单地存储http请求的结果,并在下次你的服务被注入到其他东西时检索它。
angular.module('myApp', ['ngResource']).factory('myService',
function($resource) {
var cache = false;
return {
query: function() {
if(!cache) {
cache = $resource('http://example.com/api').query();
}
return cache;
}
};
}
);
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);
});
}
在当前的稳定版本(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
});
});
一个缺点是键名也是自动设置的,这可能会使清除它们变得棘手。希望他们能以某种方式添加键名。
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请求($resource继承的)启用基本缓存:
var app = angular.module('myApp',[])
.config(['$httpProvider', function ($httpProvider) {
// enable http caching
$httpProvider.defaults.cache = true;
}])