角度服务缓存
Angular service cache
我正试图将$http的响应缓存到angular会话的对象中,因此一旦进行了初始调用,每隔一次对service.getCategories()(例如)的调用都会从对象而不是api中获取数据。
正在路由上解析服务,但存在身份验证,身份验证将重定向到另一个路由-再次调用service.getCategories()。
我试图通过在调用时设置一个init变量来实现这一点,然后所有其他调用都将直接指向填充的对象——但它似乎以某种方式重置了服务,返回的对象被填充了两次,所以所有东西都是双倍的。见下文:
var $ = require('jquery');
module.exports = angular.module('app.common.services.category', [])
.factory('categoryService', ['$http', '$q', '$rootScope', function($http, $q, $rootScope) {
// API Parameters
var deferred = $q.defer();
// Services
var Categories = {
init: false,
categories: [],
index: 0,
// Retrieve all data on load.
// Loaded into an array for all other services
// to use after init.
getCategories: function(page) {
if(!Categories.init) {
$http.get('api/core/get_category_index')
.then(function(result) {
var data = result.data.categories;
$.each(data, function(i, category) {
category.index = Categories.index;
Categories.categories.push(category);
Categories.index++;
});
Categories.init = true;
return deferred.resolve(Categories.categories);
});
// Return promise once catgories is resolved
return deferred.promise;
} else {
return Categories.categories;
}
},
allCategories: function() {
return Categories.categories;
}
}
return Categories;
}]);
您的方法的一个问题是,当第二次调用服务函数getCategories
时,第一次服务器请求可能无法解决,从而导致第二次对服务器的调用。因此,应该将init
标志直接移动到函数调用getCategories
之后。
另一个问题是,在您的情况下,您不知道函数是返回promise还是返回Array。我建议始终返回阵列
module.exports = angular.module('app.common.services.category', [])
.factory('categoryService', ['$http', '$q', '$rootScope', function($http, $q, $rootScope) {
//API参数var递延;
//服务var类别={
categories: [],
index: 0,
// Retrieve all data on load.
// Loaded into an array for all other services
// to use after init.
getCategories: function(page) {
if(!deferred) {
// replacement for intit flag
deferred = $q.defer();
$http.get('api/core/get_category_index')
.then(function(result) {
var data = result.data.categories;
$.each(data, function(i, category) {
category.index = Categories.index;
Categories.categories.push(category);
Categories.index++;
});
deferred.resolve(Categories.categories);
});
}
// always return a promise
return deferred.promise;
},
allCategories: function() {
return Categories.categories;
}
}
return Categories;
}]);
也许你可以用承诺来回报服务本身。然后你可以到处写一些东西,比如:
myService.load().then(
function success(theService) {
theService.allCategories()
}
);
现在,服务是否在之前加载已经无关紧要了
相关文章:
- 如何使用WCF服务和javascript表单post上传.doc文件
- 监视函数从服务返回不起作用,但作用域函数起作用
- 通过Magento的网络服务检索运费
- 使用服务工作者动态缓存HTTP URL的包装器
- 角度服务缓存
- 任何可用作HTML5离线缓存链接的免费服务
- 如何在从缓存加载路由后强制服务工作者从网络请求路由
- 在Angularjs服务中为返回对象引用的http请求提供的数据构建简单的缓存
- 角度服务缓存一个值
- iOS 移动 Safari 服务工作进程缓存限制
- REST 服务缓存策略与 AngularJS.
- 服务工作线程是否可以缓存 POST 请求
- 服务辅助角色缓存是否支持缓存控制标头
- JSONP 从 WCF 服务获取缓存响应时出现问题
- 在服务调用后删除缓存
- 无法在AngularJS服务中检索缓存的jQuery选择器
- $timeout保证在angular js中实现缓存服务
- Angular$http服务缓存无法正常工作
- 同步服务缓存的最佳实践是什么 Angular 1.3.
- 服务辅助角色的缓存存储的大小限制是多少