I'm trying to "cacheify" my angular service factory. I want it to use the cache to hit the URL only the first time the page is loaded. Then when I browse to my detail page (findById) I want to use the cache. Does this make sense?
Below is what I have right now but I can't figure out a solid way to handle this async. My controller is calling into the service.
angular.module('myapp.services', [])
.factory('myservice', function ($http, $q, $cacheFactory) {
var url = '//myurl.com/getawesomeJSON';
return {
findAll: function () {
var $httpDefaultCache = $cacheFactory.get('$http');
var data = $httpDefaultCache.get(url);
if (data == null) {
data = $http.get(url, { cache: true });
}
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
},
findById: function (id) {
var data = angular.fromJson($cacheFactory.get('$http').get(url)[1]);
for (var i = 0; i < data.length; i++) {
if (data[i].Id === parseInt(id)) {
var deferred = $q.defer();
deferred.resolve(data[i]);
return deferred.promise;
}
}
}
}
});