0

我正在尝试在我的 Angular 应用程序的 app.config 部分中使用 angular-cache,如此 JSFiddle 中所示 - http://jsfiddle.net/0b1jgwoj/

.config(function (componentFactoryProvider, Config, RestangularProvider, DSCacheFactory, $q) {
componentFactoryProvider.setViewPath(function (componentSnakeName, componentName) {
  return 'components/' + componentSnakeName + '/' + componentSnakeName + '.html';
})
RestangularProvider.setBaseUrl(Config.API.path);
RestangularProvider.setRequestSuffix('.json');

var appCache = DSCacheFactory('appCache', {
    maxAge: 3600000,
    deleteOnExpire: 'aggressive',
    storageMode: 'localStorage', // This cache will sync itself with `localStorage`.
    onExpire: function (key, value) {
        //Todo: implement logic to get data from server be it a collection or single object
    }
});

//Intercept the Get Request and check for value in cache. If found cancel Get Request, if not continue get Request.
RestangularProvider.addFullRequestInterceptor(function (element, operation, what, url, headers, params, httpConfig) {
        if(operation === 'get') {
            debugger;
            //Check the cache to see if the resource is already cached
            var data = appCache.get(url);
            //If cache object does exist, return it
            if (data !== undefined) {
                angular.extend(element, data);

                var defer = $q.defer();
                httpConfig.timeOut = defer.promise;
                defer.resolve();

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

RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response) {
        //Cache the response from a get method
        if(operation === 'get') {
            debugger;
            appCache.remove(url);
            appCache.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') {
            appCache.destroy();
        }

        return response;
    });

})

出现两个错误 (1) $q 未定义,即使我已将它放在 DI 列表中 (2) DSCacheFactory 正在返回一个未知的提供程序错误

关于如何解决这些问题的任何想法,因为此逻辑保留在 .config() 部分中很重要,因为 restangular 'addFullRequestInterceptor' 不会取消任何其他服务中的请求,而只会取消 config 部分。

谢谢

4

1 回答 1

1

修复了问题。必须按照本文档https://github.com/mgonto/restangular#how-to-configure-them-globally中所述将逻辑放入 .run 方法中

于 2014-09-03T15:59:35.553 回答