在AngularJS中捕获GET请求的完整URL,包括查询参数

时间:2015-03-16 22:14:47

标签: angularjs restangular cachefactory

我正在使用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);
},

配置值:http://i.imgur.com/l0IsXbJ.png

不幸的是,准备手动捕获的参数不是100%保证它将与缓存的匹配。我注意到cacheFactory检查所请求的确切字符串。因此,如果我们的GET请求的查询参数是age = 12& name = scott然后在我们的http拦截器上,我们通过将名称放在第一位然后将年龄(name = scott& age = 12),cacheFactory赢得&#来另外准备它39;找不到。

所以我试图寻找一个角度服务或工厂,它将返回与我们提出的请求相等的完整URL。我尝试了$ location但它没有提供完整的GET请求。

1 个答案:

答案 0 :(得分:0)

我刚决定解析配置并从头开始构建它。它工作得很好:))

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 ));
    }
}