0

I've created a service that fetches through $http.get().

My service is used in a directive that renders to several ui elements. The service is async. It's used in the directive code like: myService.getStuff(), and it returns a customized promise (from within the callbacks of the $http.get promise).

But I want my service to only perform one call to $http.get during the lifecycle of the app. And cache the http.get response.

So say I use the directive 2 times in my html. Then this is what I want: The first time it's called it (returns immediately and) fetches stuff via $http.get. The second time it's called it detects an outstanding call to $http.get. thus does not do another call to $http.get, but somehow awaits the return of the first call.

2 Answers 2

2

You might want to use the internal cache of $http

return $http.get(/*...*/, { cache: true }).then(/*...*/);

or just cache the promise in your service.

function MyService($http) {
   var promise;

   this.get = function() {
      promise = promise || $http.get(/*...*/).then(/*...*/);
      return promise;
   }
}

If you're using uirouter, another way is to resolve the data in a parent state, and inject the resolved data to all your components.

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

2 Comments

You have a spurious extra var inside the function. It needs to just be an assignment to the outer promise variable.
so setting cache: true, won't work in my case since what I want to avoid is calling $http.get(), regardless of if it internally caches the response. But as you write caching the promise in my service might be more along the lines. This means that I would return the same promise several times and set different callback functions to it each time the service is called. Is this fine?
0

Set cache to true like this:

$http.get(yourUrl, {cache: true})
    .then(...)

Any subsequent call to this will use the cached value.

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.