Angular JS异步两个API请求

时间:2013-03-15 16:31:00

标签: angularjs

目前在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同时请求两个,所以完整的请求不是一个+另一个 - 但是他们都返回的最快时间。

1 个答案:

答案 0 :(得分:0)

如果要在两个查询完成后触发回调,请将其放在$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