0

I'm fetching some data with $http in a controller to show the user some data. But after this is done I don't want to do anymore fetches because the data is already fetched. However when going from one tab (controller) to another tab (controller) data is always fetched. My knowledge is limited to web and AngularJS. I thought below code would work but data is always fetched.

// We already have data don't bother to get it again
if (angular.isDefined($scope.data)) {
    console.log("Already got data, no fetch");
    return;
} else {
    console.log("Fetch data first time");
}

$http.post('/api/data'......

1 Answer 1

2

Most likely (although, there isn't enough code in your example to be certain) your tab controllers have different scopes, so $scope.data is actually not defined for the second tab (controller).

You could certainly put the data on $rootScope but I would recommend against that, as I would against a global variable.

Also, you'd have a race condition here because you might switch tabs before the data arrived and that would trigger a second request.

A good way to solve this is with a service. The service can cache the promise and return that to the next caller.

.factory("fooSvc", function($http){
  var promise;
  return {
    getData: function(){
       if (promise) return promise;
       promise = $http.get("/some/url").then(function(response){
         // optionally post-process the response
         return response.data;
       });

       return promise;
    }
  }
})

Then, in the controller you could just get the data and not worry about duplicate calls:

.controller("TabCtrl1", function($scope, fooSvc){
   fooSvc.getData().then(function(data){
     $scope.data = data;
   })
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your input. I think I forgot to add some information that the controllers fetch different data (not the same data as your assumption). Is your approach still feasible? To clarify, when switching tabs I don't want to fetch data if the data has already been fetched to speed things up (updates will go out through a websocket). However on refresh/reload of the tab the data should be fetched.
You can always use cache: $http.get(url, {cache: true})
So you're saying using cache is "equivalent" of using a factory and caching the data in the factory?
To the extent that it caches based on a key (url + query params). You could do the same with a service manually. There's not much difference there, unless your post-processing is significant and you wouldn't want to repeat.

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.