我正在尝试在我的角度应用程序的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'不会在任何其他服务中取消请求,只会取消配置部分。
由于
答案 0 :(得分:1)
修正了问题。必须按照本文档https://github.com/mgonto/restangular#how-to-configure-them-globally
中的说明将逻辑放在.run方法中