Manolo
Manolo

Reputation: 1676

Avoid multiple $http.get in async service

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.

Upvotes: 0

Views: 39

Answers (2)

hansmaad
hansmaad

Reputation: 18905

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.

Upvotes: 2

Nasreddine
Nasreddine

Reputation: 37798

Set cache to true like this:

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

Any subsequent call to this will use the cached value.

Upvotes: 0

Related Questions