在Angular中,我有这样的代码:
app.factory("myService", function($http, $q) {
return {
doBoth: function(data) {
return $q.all([$http.post("/search/local", data), $http.post("/search/shape", data)]);
}
};
});
我这样称呼它:
$scope.$on("localSearch", function(event, data) {
return myService.doBoth(data);
});
然而,我不认为这是异步发生的。它们都需要相当长的时间来完成,所以我需要Angular同时请求两个,所以完整的请求不是一个+另一个,而是它们同时返回的最快时间。
如果你想在两个查询完成后触发回调,把它放在$q.then()
方法中。
$scope.$on("localSearch", function(event, data) {
return myService
.doBoth(data)
.then(function (response) {
// both deffered completed
});
});
我在这里创建了示例http://plnkr.co/edit/7G8oFMSx8cPC98zDhlNq?p=preview