Reputation: 139
I have a service I'm using to fetch data for an application.
Since a service is a singleton, I'd like to cache some reference data in the service, but I'm not sure how to get that to happen.
I'm using Strongloop and right now have a function in the Service like this:
function fetchReferenceData() {
return refInfo.find().$promise;
}
I'd like to have a property where I store the reference data. I could add a property in the code, like var myRefData;
and then I could edit fetchReferenceData() to check that property, but since the client is expecting a promise back, this won't work:
function fetchReferenceData() {
if (myRefData) { return myRefData; }
else { return refInfo.find().$promise;}
}
What's a good programming pattern to work with this kind of thing? Do I pass in a function to call in a .then() to set the data in the client?
Upvotes: 0
Views: 113
Reputation: 48968
If the client is expecting a promise, you can use the $q
service to create a promise from your cached value.
function fetchReferenceData() {
if (myRefData) { return $q.when(myRefData); }
else { return refInfo.find().$promise;}
}
The client can access it with the standard .then
method.
fetchReferenceData().then (function (myRefData) {
//use myRefData
});
Best practices
You need a way to destroy the information in your cache.
You need to avoid calling refInfo.find()
again if a query is already in progress.
Methods from Angular $resource
services return references to empty objects.
From the Docs:
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on
isArray
). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.
So you can cache the query reference but you need to be aware the data on it will be undefined for a period of time.
The $resource
service also adds a $promise
property that can be used by clients that accept a promise.
function fetchReferenceData() {
var cache;
return cache = cache || refInfo.find();
}
clientThatNeedsPromise(fetchReferenceData().$promise);
Upvotes: 1