AngularJS:收到响应之前避免调用相同的REST服务两次 [英] AngularJS: Avoid calling same REST service twice before response is received
问题描述
我有两个指令,每消耗相同包装厂一$ Q / $ HTTP调用。
I have two directives, each consuming the same factory wrapping a $q/$http call.
angular.module("demo").directive("itemA", ["restService", function(restService) {
return {
restrict: "A",
link: function(scope, element, attrs) {
restService.get().then(function(response) {
// whatever
}, function(response) {
// whatever
});
}
};
}]);
angular.module("demo").directive("itemB", ["restService", function(restService) {
return {
restrict: "A",
link: function(scope, element, attrs) {
restService.get().then(function(response) {
// whatever
}, function(response) {
// whatever
});
}
};
}]);
angular.module("demo").factory("restService", ["$http", "$q", function($http, $q) {
return {
get: function() {
var dfd = $q.defer();
$http.get("whatever.json", {
cache: true
}).success(function(response) {
// do some stuff here
dfd.resolve(response);
}).error(function(response) {
// do some stuff here
dfd.reject(response);
});
}
};
}]);
问题:当我做到这一点。
Problem: When I do this
<div item-a></div>
<div item-b></div>
我得到同样的Web服务发射了两次,因为从意达的GET仍在进行中时ItemB的GET去。
I get the same web service fired off twice, because the GET from ItemA is still in progress when the GET for ItemB goes.
是否有任何火灾第二要知道,有已经到这个请求的进步,以便它可以等待一分钟,并抓住它免费的方式?
Is there a way for whichever fires second to know that there's already a request to this in progress, so that it can wait a minute and grab it for free?
我想过作出$ http或$ Q封装程序或标志的每个网址为待定不是,但我不知道这是最好的方式。我会怎么做,如果它挂起?刚刚返回现有的承诺,它会解决其他结算时什么时候?
I've thought about making an $http or $q wrapper which flags each URL as pending or not but I'm not sure that's the best way. What would I do if it was pending? Just return the existing promise and it'll resolve when the other resolves?
推荐答案
是的,所有你需要做的是缓存的承诺,清理关闭请求完成后。在两者之间可以只使用了同样的承诺的任何后续请求。
Yes, all you need to do is to cache the promise and clean it off after the request is done. Any subsequent request in between can just use the same promise.
angular.module("demo").factory("restService", ["$http", "$q", function($http, $q) {
var _cache;
return {
get: function() {
//If a call is already going on just return the same promise, else make the call and set the promise to _cache
return _cache || _cache = $http.get("whatever.json", {
cache: true
}).then(function(response) {
// do some stuff here
return response.data;
}).catch(function(response) {
return $q.reject(response.data);
}).finally(function(){
_cache = null; //Just remove it here
});
}
};
}]);
这篇关于AngularJS:收到响应之前避免调用相同的REST服务两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!