Reputation: 1687
Let us say I have 4 views in my application . Home, Product, Login, Upload.
currently I am at Login View , after Login I am redirected to Product view. Now for product view, I have a directive controller function something like below
function directiveController(){
var self=this;
init();
function init(){
service.getProducts(parameter1, parameter2, successCallback, error);
}
}
service.getProducts()
will call the service and display the products. Now the problem is suppose I am at Upload view or any other view, and I am moving to again to Product view this service is getting calling again and again. I dont want it, I want once after login into the application this service should get called only one time and not every time.
I dont want to use $rootScope
to implement this functionality any where in my application.
Any help, ideas, suggestion is appreciated.
Thanks
Upvotes: 0
Views: 95
Reputation: 407
You could use an Angular cache to store the data for a specific period of time: https://docs.angularjs.org/api/ng/service/$cacheFactory
This way you can implement your logic on how much you want or need this to be cached.
var cache = $cacheFactory('service-name-cache'),
cacheKey = someSessionHash + elementKey,
data = cache.get(cacheKey;
if (!data) {
service.getProducts().success(function(result) {
data = result;
cache.put(cacheKey, data);
});
Upvotes: 0
Reputation: 23622
Have a sort of factory/service
like activeModel
which would hold the values for the getProducts
api call, then you could check whether the activeModel holds some data, then you are not making the call.. else you would make the api call.
(function () {
'use strict'
angular.module('your-module')
.factory('activeModel', activeModel);
function activeModel(){
var activeModel = {};
activeModel = {
products : {},
};
return activeModel;
}
})();
Then inside your init method, you can check like this..
function init(){
if(!Object.keys(activeModel.products).length > 0){
//or you can check for some properties/values too here..
service.getProducts(parameter1, parameter2, successCallback, error);
}
}
Another simpler solution would be to move the api call to your controller
by abstracting the api call to your factory/service
.
Upvotes: 2