angularjs - AngularJS 拦截器 - 将响应数据修改为缓存数据
问题描述
我想用 etags 和角度拦截器创建一个缓存解决方案。一切正常,但我无法返回缓存的数据。我想304 Not Modified
用缓存的数据覆盖响应。
'responseError': function(rejection) {
if(rejection.status === 304){
var response = {};
var url = rejection.config.url;
var params = rejection.config.params || {};
var etagKey = url+'.'+JSON.stringify(params);
var storedValue = $localStorage['ETag-Cache'+etagKey] || '{}';
var cachedObj = JSON.parse(storedValue);
console.log('CACHED ETag-Cache'+etagKey,cachedObj.response);
//I'd like to return with the cached data here but this doesn't work
return cachedObj.response;
}
return $q.reject(rejection);
}
下面的示例请求
$http.get('/api/bigdata', {
}).then(function(resp){
//I'd like to get the cached data in the resp variable
});
解决方案
我还没有找到解决方案,但我有一个解决方法。由于304
错误状态的问题,我发送回一个状态代码200
,而不是一个自定义标题:Not-Modified = 1
和一个空响应,然后我在拦截器中处理这个。
Laravel ETag MiddleWare 中的伪代码
if ($requestEtag && $requestEtag[0] == $etag) {
$response->setStatusCode(200);
$response->header('Not-Modified', true);
$response->setContent('{"status":"Not-Modified"}');
}
AngularJS 拦截器响应处理程序:
//Etag Handler
var url = res.config.url;
var params = res.config.params || {};
var etag = res.headers().etag;
var etagKey = url+'.'+JSON.stringify(params);
var EtagVal = JSON.stringify(
{
'etag':etag,
'url':url,
'params':params,
'response':res.data
});
//If Not-Modified header is true
if(res.headers()['not-modified'] == "1"){
var storedValue = $localStorage['ETag-Cache'+etagKey] || '{}';
var cachedObj = JSON.parse(storedValue);
console.log('CACHED ETag-Cache'+etagKey,cachedObj.response);
res.data = cachedObj.response;
return res || $q.when(res);
}
这样我就可以获取缓存值,$http.then(response)
而不是从服务器下载整个数据。
推荐阅读
- python - 在 Jupyter 中将警告变成错误
- ruby-on-rails - Twilio 消息价格
- python - Django如何从列表中将对象保存在for循环中
- python - 使用 Homebrew 安装 Python 后找不到 IDLE
- javascript - 滚动时 HTML 高度发生变化 - 生成页面内容上方的空间
- azure-service-fabric - 证书问题 - Service Fabric 卡在“等待节点”上
- javascript - 如何使用 javascript 按钮停止我的接收功能(通道 websocket)
- json - 在查询的地图上应用周围的 html 元素
- javascript - 如何在 React Native 中共享消息或邮件上的 pdf 文件
- layout - 可以创建一个现有布局的对话框,保留类的方法吗?