AngularJS 工厂函数无法访问本地存储的缓存变量
AngularJS factory function cannot access a locally stored cache variable
在
这一点上,我已经在这里呆了10多个小时。这对我来说没有意义。我迫切需要澄清我做错了什么。下面是一个简单的工厂函数,它对 JSON 文件进行 AJAX 调用。没有异步。数据问题和一切正常。我遇到的问题是我正在尝试保存返回的结果并稍后访问它。如果变量被填充,我就不必进行第二次 AJAX 调用,我可以简单地获取局部变量的内容。我意识到还有其他方法可以做到这一点,但我特别喜欢使用这种工厂方法。
storyDataAsFactory.$inject = ['$log', '$http', '$q'];
angular.module('ccsApp').factory('storyDataAsFactory', storyDataAsFactory);
function storyDataAsFactory($log, $http, $q) {
var storiesCache = [];
function getStories(url) {
url = url || '';
if (url !== '') {
var deferred = $q.defer();
alert('inside getStories, length of storiesCache = ' + storiesCache.length); // this is always zero! Why?
//determine if ajax call has already occurred;
//if so, data exists in cache as local var
if (storiesCache.length !== 0) {
$log.info('Returning stories from cache.');
deferred.resolve(storiesCache);
return deferred.promise;
}
$http({method:'GET', url:url})
.success(function (data, status, headers, config) {
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
} else {
$log.error('(within storyDataAsFactory) Failed to retrieve stories: URL was undefined.');
}
}
return {
stories: storiesCache,
getStories: function(url) {
alert('inside return factory object, length of stories = ' + this.stories.length);
//getStories returns a promise so that routeProvider
//will instantiate the controller when resolved
return getStories(url);
}
};
}
你需要使用一个承诺。我没有运行下面的代码,但这就是这个想法:
angular.module('ccsApp').service('storyDataAsFactory', storyDataAsService);
function storyDataAsService($log, $http, $q) {
var storiesCache = [];
function getStories(url) {
url = url || '';
if (url !== '') {
alert('inside getStories, length of storiesCache = ' + storiesCache.length); // this is always zero! Why?
if (storiesCache.length == 0) {
return $http({method:'GET', url:url});
} else {
var deferred = $q.defer();
deferred.resolve(storiesCache);
return deferred.promise;
}
} else {
$log.error('(within storyDataAsFactory) Failed to retrieve stories: URL was undefined.');
}
}
return {
getStories: function(url) {
return getStories(url).then(function(stories) {
// Do whatever
return stories;
});
}
};
}
storyDataAsService.getStories().then(function(stories) {
$scope.stories = stories
})
相关文章:
- 将脚本缓存到本地存储的basket.js概念仍然是一个好主意吗
- “DOMException:找不到条目”时将大型响应放入缓存存储
- HTML5 本地存储作为缓存和单个资产请求
- 如何在浏览器中存储缓存
- 如何使用jquery将ajax响应存储在浏览器缓存中
- 将此 pdf 保存在 ionic 上的缓存/本地存储中
- AngularJS 工厂函数无法访问本地存储的缓存变量
- 如果我存储缓存并且已达到缓存限制会发生什么
- 如何验证“缓存控制”、“无缓存、无存储、必须重新验证”
- HTML5应用程序缓存文件存储在客户端的位置
- 缓存 Web 应用程序界面并使用 html5 本地存储恢复它
- Extjs 4 存储 - 查询整个存储,而不仅仅是缓存的记录
- 客户端存储/缓存大型HTML
- 将图像存储在浏览器缓存中-加载图像的最佳方式
- 显示缓存中存储的内容
- 如何在HTML5'中存储50MB视频;s应用程序缓存
- HTML5本地存储VS应用缓存离线网站浏览
- 如何在iOS中存储UIWebView缓存,使其在页面打开时不会闪烁
- 为什么这些记录不存储在缓存中
- 在HTML5本地存储中缓存整个jquery.min.js文件