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;
}
}
}
}
});
I haven't tested this since you didn't provide a plunker, but the following should set you in the right direction. You need to make use of promise chaining.
angular.module('myapp.services', [])
.factory('myservice', function ($http, $q, $cacheFactory) {
var url = '//myurl.com/getawesomeJSON';
return {
findAll: function () {
var $httpDefaultCache = $cacheFactory.get('$http');
var deferred = $q.defer();
var data = $httpDefaultCache.get(url);
if (!data) {
$http.get(url, { cache: true }).then(function(result){
deferred.resolve(result);
});
} else {
deferred.resolve(data);
}
return deferred.promise;
},
findById: function (id) {
return this.findAll().then(function(data) {
for (var i = 0; i < data.length; i++) {
if (data[i].Id === parseInt(id)) {
return data[i];
}
}
return $q.reject('Not found'); // id not found
});
}
}
});