我正在使用http拦截器。当我发出 Restangular GET 请求时,我确实看到了所有值。这是我的请求拦截器的代码。
request: function (config) {
// see link below to see value of config
console.log('config', config);
// below returns full url except query string
console.log('location', $location.absUrl());
// $rootScope.cacheData is $cacheFactory
console.log('$rootScope', $rootScope.cacheData);
// only returns {id: "http", size: 3}
console.log('cache info', $rootScope.cacheData.info());
// below returns undefined
console.log('cache get', $rootScope.cacheData.get('http'));
// other codes removed since it's not related
// ........
// ........
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
配置值:https://i.stack.imgur.com/IlY75.png
不幸的是,准备手动捕获的参数并不能 100% 保证它与缓存的内容匹配。我注意到cacheFactory检查请求的确切字符串。因此,如果我们的GET请求的查询参数是age=12&name=scott,那么在我们的http拦截器上,我们以另一种方式准备它,将name放在第一位,然后是age(name=scott&age=12),cacheFactory不会找到它。
所以我正在尝试寻找一个角度服务或工厂,它将返回与我们发出的请求相等的完整 URL。我试过$location但它没有给出完整的 GET 请求。
我只是决定解析配置并从头开始构建它。它工作得很好:)
if ( config.method == 'GET' && (config.url.indexOf('v1/repeters') != -1) ) {
// Prepare the full path
var cachedUrlsLocalStorage;
var absolutePath = '';
_(config.params).keys().sort().each( function(key, index) {
var value = config.params[key];
absolutePath = absolutePath + key + '=' + value + (index < _(config.params).keys().value().length - 1 ? '&' : '');
});
cachedUrlsLocalStorage = JSON.parse(window.localStorage.getItem('cachedUrls'));
if (cachedUrlsLocalStorage) {
var exists = _.findIndex(cachedUrlsLocalStorage, function(cachedData) {
return cachedData.url == config.url + '?' + absolutePath;
});
if (!exists) {
cachedUrlsLocalStorage.push({url : config.url + '?' + absolutePath, timeExecuted : moment(), expiryTime : moment().add(10, 'minutes')});
window.localStorage.setItem('cachedUrls', JSON.stringify( cachedUrlsLocalStorage ));
}
} else {
cachedUrlsLocalStorage = [];
cachedUrlsLocalStorage.push({url : config.url + '?' + absolutePath, timeExecuted : moment(), expiryTime : moment().add(10, 'minutes')});
window.localStorage.setItem('cachedUrls', JSON.stringify( cachedUrlsLocalStorage ));
}
}