在AngularJS中捕获GET请求的完整URL,包括查询参数
我正在使用http拦截器。当我发出重新启动的GET请求时,我确实看到了所有的值。这是我的请求拦截器的代码在AngularJS中捕获GET请求的完整URL,包括查询参数,angularjs,restangular,cachefactory,Angularjs,Restangular,Cachefactory,我正在使用http拦截器。当我发出重新启动的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
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);
},
配置值:
不幸的是,准备手动捕获的参数并不能100%保证它与缓存的参数匹配。我注意到cacheFactory检查请求的字符串。因此,如果GET请求的查询参数是age=12&name=scott,那么在http拦截器上,我们以另一种方式准备它,首先是name,然后是agename=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 ));
}
}