1

I have a service "OneTimeService" that has a "init" method.

 // Within OneTimeService code
var this = self;
this.init = function() {
 return $http..... function(data) {
     self.data = data
 }
}

Inside of each of my controllers that are associated with my routes, I have a : // Within some controller code OneTimeService.init().then(data) { $scope.somevariable = data.someattribute; // do other stuff }

The problem I have is, I have 10 different "routes". Each of them has the:

 // Within every controller (assuming each route I have uses a different controller) code but injects the OneTimeService.
OneTimeService.init().then(data) {
$scope.somevariable = data.someattribute;
// do other stuff
}

Everytime I call "init()", it performs an $http request, when in actuality, all I want is to be able to call it ONE TIME EVER in my application $http request, then use the cached variable "self.data" from the service. The reason why I like the .then is it guarantees that I have "self.data" set within the OneTimeService prior to doing anything else. Are there alternatives?

What is the best way to do this?

1 Answer 1

2

I'd cache the data on the OneTimeService where I check if the data already exists (from previous call) or not, and using a promise like the $q service:

1- If the data NOT exists, I'll let the $http service call the server to retrieve the data and then I can cache it in a variable inside the service.

2- If the data does exist, resolve the promise straight away using the cached data and return.

So something like this :

// in OneTimeService code

var _cachedData = null;

this.init = function() {
    var def = $q.defer();

    // check if _cachedData was already cached
    if(_cachedData){
        def.resolve(_cachedData);        
    }

    // call the server for the first and only time
    $http.get(url).then(function(data) {
        // cache the data
        _cachedData = data;
        def.resolve(_cachedData);
    }, function(err){
        def.reject(err);
    });
    return def.promise;
}

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.