0

What is the best way in AngularJs to save or cache temporary somewhere the resource result in order multiple directive which need the resource result to get it without requesting again and again the same resource in the server?

Imagine having 5 directives which all of them need the result of resource

http://foo.com/accounts

This returns a json of accounts (REST API GET method).

What is the best practice to cache result of this resource or save it to a variable and then each directive get the data from this variable and avoid hitting the rest API more than once every 1 minute (so cache expires in 1 minute)

Thanks a lot.

1 Answer 1

2

There are a few ways to accomplish this but one simple self contained way would be something like this:

app.factory('myFactory', function($http) {
  var THRESHOLD = 60000; // 60 seconds
  var request = null;
  var timestamp;

  var service = {
    getResource: function() {
      var now = new Date().getTime();

      // only make a request if we haven't made one yet
      // or if its been longer than 60 seconds since the last request
      if(request === null || timestamp && now - timestamp > THRESHOLD) {
        timestamp = now;
        request = $http.get('http://some.service.com/resource');
      }

      // we're always returning a promise, once its resolved any service that
      // calls getResource won't have to wait for the request unless its been
      // over 60 seconds since the last one.
      return request;
    }
  }

  return service;
});

Basic demo here(modified slightly to simulate the http request): http://plnkr.co/edit/QncVlV?p=linter

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

4 Comments

Is it possible somehow the service return the real data and not the promise? I want in controller do that: $scope.data = myFactory.getResource(); instead of myFactory.getResource().then(function(data) { $scope.data = data; });
For that you can setup a resolve if you are using ui-router or ngRoute. See examples here: odetocode.com/blogs/scott/archive/2014/05/20/…
Can I use resolve in directives? The objective is to get the resource result inside a directive
Ah, unfortunately I am not aware of a resolve for directives even though it looks like a ton of people are wanting something like that: github.com/angular/angular.js/issues/2095. You could have a loading spinner or something that displays until the promise is resolved - not ideal but maybe a decent compromise.

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.