Reputation: 3109
I have a $resource, which I am using for fetching one or all Registrations, creating new or update existing Registrations, deleting registrations... the works. Here's the code of the resource:
.factory('Registrations', function ($resource) {
return $resource('api/registrations/:assetType/:registrationId',
{assetType: '@assetType', registrationId: '@assetRegistrationId'},
{query: {
method: 'GET',
cache: true,
isArray: true
}}
);
})
As you can see, caching is put in place, and this works fine: subsequent requests aren't propagated to the server. Except... after the creation or the removal of a Registration, the cache isn't updated.
For the removal I have come up with this workaround. It looks terrible but it works. There's some strange things to notice though:
Registrations.delete({assetType: $scope.assetType, registrationId: registration.assetRegistrationId}, function () {
//doesn't seem to work -> dirty hack
//$cacheFactory.get('$http').remove('api/registrations/' + $scope.assetType + '/' + registration.registrationId);
var cached = $cacheFactory.get('$http').get('api/registrations/' + $scope.assetType);
var cachedRegistrations = JSON.parse(cached[1]);
var registrationInCache = get(cachedRegistrations, registration.assetRegistrationId);
if (registrationInCache) {
cachedRegistrations.splice(cachedRegistrations.indexOf(registrationInCache), 1);
cached[1] = JSON.stringify(cachedRegistrations);
}
$scope.registrations = Registrations.query({assetType: $scope.assetType});
//...
The surprising thing is that the cache doesn't keep a list of javascript objects, but just 1 entry with a an actual string representing the json of all items. What I'm doing is then jsonifying that string, removing the deleted item and stringifying the list again.
For the creation I haven't been that creative, and I can only remove that one entry (representing the complete collection) in the cache and reload all the data from the server. Here's how I invalidate the cache.
$cacheFactory.get('$http').remove('api/registrations/' + $scope.assetType);
I'm probably missing something obvious. Anybody any suggestions or clarifications? Thanks!
Upvotes: 0
Views: 314
Reputation: 7279
I believe this kind of caching should be done on the server side, not on the front-end (AngularJS). I'm not 100% sure how Angular's cache=true
work but I believe it just caches the result so additional requests will get the cached results. Angular can't tell when the data on your server has changed.
Upvotes: 1