Захват полного URL запроса GET в AngularJS, включая параметры запроса

Я использую http перехватчик. Я вижу все значения при выполнении запроса Restrict 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-запроса имеют возраст =12&name=scott, то на нашем http-перехватчике мы подготовим его другим способом, указав сначала имя, а затем age(name=scott&age=12), cacheFactory не найдет его.

Поэтому я пытаюсь найти угловой сервис или фабрику, которая будет возвращать полный URL-адрес, равный запросу, который мы сделали. Я пробовал $location, но он не дает полный запрос GET.

1 ответ

Я просто решил разобрать конфиг и собрать его с нуля. Работает отлично:)

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 ));
    }
}
Другие вопросы по тегам