4
我已经实现了自定义的功能和参数的角度$资源,如下所示: -
.factory('CandidateService', ['$resource', function ($resource) {
return $resource("api/:action/:id", {},
{
'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: true },
'getCandidate': { method: 'GET', params: { action: "Candidate", id: "@id" } }
});
}]);
,我在控制器消费此如下: -
.controller('Controller', ['CandidateService', function ($scope, CandidateService) {
$scope.candidateList = [];
CandidateService.getAll(function (data) {
$scope.candidateList = data;
});
}]);
这工作非常好。现在我需要将api中的数据缓存到CandidateService Factory中,以便它不会被加载eveytime我在控制器之间移动。
所以我想我会如下做些什么: -
.factory('CandidateService', ['$resource', function ($resource) {
var Api = $resource("api/:action/:id", {},
{
'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: true },
'getCandidate': { method: 'GET', params: { action: "Candidate", id: "@id" } }
});
var candidateDataLoaded = false;
var candidateData = [];
return {
getCandidates: function() {
if (!candidateDataLoaded) {
Api.getAll(function (data) {
angular.copy(data, candidateData);
});
}
return candidateData;
}
}
}]);
但我只是不能得到这个工作。我认为这与作为单身人士的角质工厂有关。
我的方法是否正确实施缓存?
可能重复(http://stackoverflow.com/questions/12225475/angularjs-how-to-add-缓存到资源对象) – pilau
伟大而简洁的答案在这里:http://stackoverflow.com/a/16080092/1049693 – pilau