6

我创建了一个 UserService 如下:

angular.module('nrApp').factory('userService', ['Restangular', 'UserModel', 'DSCacheFactory', function (Restangular, UserModel, DSCacheFactory) {
    // Create a new cache called "profileCache"
    var userCache = DSCacheFactory('userCache', {
        maxAge: 3600000,
        deleteOnExpire: 'aggressive',
        storageMode: 'localStorage', // This cache will sync itself with `localStorage`.
        onExpire: function (key, value) {
            Restangular.oneUrl('users', key).get().then(function(data) {
                userCache.put(key, data);
            });
        }
    });

    Restangular.extendModel('users', function(obj) {
        return UserModel.mixInto(obj);
    });

    Restangular.addRequestInterceptor(function(element, operation, what, url) {
        if(operation === 'get') {
            debugger;
            //Check the cache to see if the resource is already cached
            var data = userCache.get(url);
            //If cache object does exist, return it
            if(data !== undefined) {
                angular.extend(element, data);
            }

            return element;
        }
    });

    Restangular.addResponseInterceptor(function(data, operation, what, url, response) {
        //Cache the response from a get method
        if(operation === 'get') {
            debugger;
            userCache.put(url, data);
        }

        //Unvalidate the cache when a 'put', 'post' and 'delete' is performed to update the cached version.
        if (operation === 'put' || operation === 'post' || operation === 'delete') {
            userCache.destroy();
        }

        return response;
    });

    return Restangular.service('users');
}]);

从评论中可以看出,我想要实现的是,每当使用 Restangular 通过此服务执行 Get 请求时,都会检查本地缓存,如果缓存返回一个对象,则将其扩展到 restangular 元素。想要实现的流程是在为该请求找到缓存对象时取消对该服务器的请求。

然而,即使在缓存中找到对象,addResponseInterceptor 方法仍然会执行,但运气不佳。

在“获取”请求期间是否有任何可能的解决方案来取消对服务器的请求?

谢谢!:)

4

3 回答 3

3

一种解决方法是通过 httpConfig 取消它。Restangular 为您提供 httpConfig 对象作为addFullRequestInterceptor方法中的参数。你可以像下面这样使用它:

RestangularProvider.addFullRequestInterceptor(function(element, operation, what, url, headers, params, httpConfig ) {
    ...
    if found in cache {
        var defer = $q.defer();
        httpConfig.timeOut = defer.promise;
        defer.resolve();
    }
    ...
}

希望这可以帮助。

于 2014-09-02T18:09:00.200 回答
1

我通过简单地更改 RequestInterceptor 中的 httpConfig 设置解决了返回缓存数据的特定问题(如果可以通过 angular-cache CacheFactory 实例获得)。示例如下所示:

angular.module('App')
.factory('Countries', function (Restangular, CacheFactory, $q) {

    var countryCache;
    var countryService;

    // Check to make sure the cache doesn't already exist
    if (!CacheFactory.get('countryCache')) {
        countryCache = CacheFactory('countryCache', { maxAge: 60 * 60 * 1000 });
    }

    if (!countryService) {
        countryService = Restangular.service('countries');

    Restangular.addFullRequestInterceptor(function(element, operation, what, url, headers, params, httpConfig) {

            if (what === 'countries') {
                switch (operation) {
                    case 'getList':
                        httpConfig.cache = countryCache;
                        break;

                    default:
                        break;
                }               
            }

            return { 
                element: element,
                headers: headers,
                params: params,
                httpConfig: httpConfig
            };

        });

    }

    return countryService;
});
于 2015-04-01T03:18:24.873 回答
0

您可以装饰 $http 以防止对同一 url 的多个请求。Restangular 使用 $http,不需要添加 fullRequestIntercepter 来取消请求,因为这会在发送前阻止请求。

    $provide.decorator('$http', function ($delegate, $cacheFactory, $rootScope) {
    var $http = $delegate;
    var customCache = $cacheFactory('customCache');
    var wrapper = function () {
        var key = arguments[0].url;
        var requestPromise = customCache.get(key);
        if (!requestPromise){
            $rootScope.requestCount++;
            requestPromise = $http.apply($http, arguments);
            requestPromise.then(function(){
                customCache.remove(key);
            });
            customCache.put(key, requestPromise)
        }
        return requestPromise;
    };

    Object.keys($http).filter(function (key) {
        return (typeof $http[key] === 'function');
    }).forEach(function (key) {
        wrapper[key] = function () {
            return $http[key].apply($http, arguments);
        };
    });

    return wrapper;
});

这里的例子

于 2015-02-16T05:36:33.163 回答