Paw*_*lai 18 javascript asp.net json caching angularjs
如何缓存从$ http调用返回的json数据.我使用以下$ http调用样式:
$http({
url: 'SomeWebMethodUrl',
method: "POST",
data: "{'query':'somevalue'}",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
//something in success
}).error(function (data, status, headers, config) {
//something in error
});
Run Code Online (Sandbox Code Playgroud)
我查看了以下教程:https : //coderwall.com/p/40axlq来自$ http调用的缓存服务器响应.但它解释了$ http.get()样式并将缓存数据,如果绝对URL相同,则不会产生第二个$ http请求.
当我的'data'属性对于将来的相同webmethod调用相同时,我可以使用我的$ http调用样式进行缓存吗?我在WebMethods上使用ASP.net ASMX webservice.
Geo*_*enz 32
angular.js缓存仅用于HTTP GET调用.这与HTTP协议的意图一致,因为HTTP服务器通常不会超出URL,HTTP方法和Cache-Control标头来确定它们是否可以响应具有缓存内容的请求.因此,angular的作者没有将缓存功能扩展到其他HTTP方法.
查看它的另一种方法是,角度$ cache服务实际上只是一个简单的键值存储,请求的URL充当键,对HTTP GET的响应请求本地存储的值而不是服务器.
当你以这种方式想到它时,很明显为什么将响应缓存到POST请求更加困难.POST请求返回的内容不仅取决于URL,还取决于POSTed内容.要将结果缓存在键值存储中,您需要一种机制来创建唯一键,以标识URL和传递的数据.
如果您的数据足够简单,我建议您在使用angular $ http服务之前编写自己的缓存.在不了解您的数据方法的情况下,我无法给您一个完整的示例,但您可以执行以下操作:
angular.module('myModule').service('myDataService', function($cacheFactory, $http) {
var cache = $cacheFactory('dataCache');
function success(data, status, headers, config) {
// some success thing
}
function error(data, stats, headers, config) {
// some error thing
}
this.getSomeData = function(url, query) {
var cacheId = url + '*' + query;
var cachedData = cache.get(cacheId);
// Return the data if we already have it
if (cachedData) {
success(cachedData);
return;
}
// Got get it since it's not in the cache
$http({url: url,
method: 'POST',
data: {query: query},
headers: { 'Content-Type': 'application/json' } // Probably not necessary, $http I think does this
}).success(function(data, status, headers, config) {
// Put this in our cache using our 'unique' id for future use
cache.put(cacheId, data);
success(data, status, headers, configs);
}).error(error);
};
});
Run Code Online (Sandbox Code Playgroud)
然后,您将替换当前使用原始$ http服务的此包装器服务.
重点是在实际调用$ http服务之前实现自己的缓存,将"url + data"理解为一个键.
| 归档时间: |
|
| 查看次数: |
16441 次 |
| 最近记录: |