Angularjs:重新使用未解决的承诺来阻止多$ http呼叫?

时间:2015-09-22 00:03:53

标签: angularjs promise

我需要directive中的一些异步数据,这个指令会重复,因此,当应用程序启动时,每个directive都会调用服务数据,但由于仍然没有缓存数据,{{ 1}}被执行多次。

我在服务中添加了一个承诺,并尝试将其返回而不是新的。它似乎有效,但我不知道这是不是一个好主意?

$http

1 个答案:

答案 0 :(得分:0)

当然,您可以缓存承诺并将其返回给下一个调用者,除非它可能(可能应该)在没有$q.defer的情况下完成 - 我稍后会介绍。

由于您的问题特定于$http,因此更简单的方法是使用带有{ cache: true }的$ http内置缓存作为配置:

app.factory("User", function($http){
  var svc = {
     getAll: function(){
       return $http.get("api/users", { cache: true })
                   .then(function(response){
                      return response.data;
                   });
     }
  };

  return svc;
})

如果你想缓存承诺本身 - 当你做的不仅仅是纯$http时很有用 - 你可以这样做并将其返回给下一个调用者。您不需要使用$q.defer,因为$http(或其他基于promise的API)已经返回了一个promise,所以只需缓存它。您甚至可以使用$cacheFactory

var usersCache = $cacheFactory("users");
svc.getUserDetails: function(userId){

   var promise = usersCache.get(userId) || 
                 $http.get("api/users/" + userId)
                      .then(doSomethingCrazy)
                      .then(doSomethingCrazier);

   usersCache.put(userId, promise);

   return promise;

}