Angular.js等待多个资源(ajax)调用

时间:2014-09-15 15:54:14

标签: javascript angularjs coffeescript

我有一个Angular.js应用程序,我需要调用三个不同的资源,一旦完成,就一起使用它们。我的三个电话就在下面。

# Get the curriculum
$scope.curriculum = CurriculumResource.get id: $routeParams.id

# Get the list of courses
$scope.courses = CourseResource.query()

# Get the list of groups
$scope.groups = GroupResource.query()

一旦我知道请求全部完成,我怎么能执行更多逻辑。我尝试使用下面显示的$ watchGroup和$ watchCollection但似乎都没有工作。

$scope.$watchGroup ['curriculum', 'courses', 'groups'], ->
    # Shouldn't this run each time something in the above array changes?
    console.log 'Only runs once'

    # The values of the items in the below if statement eventually give a true result
    # but the if statement never runs when they are true
    if $scope.curriculum.groups and $scope.groups.length          
      console.log 'never gets here!'

2 个答案:

答案 0 :(得分:2)

我相信你可以用$q.all来完成这个,假设你的所有请求都返回了promises。像

这样的东西
$q.all([CurriculumResource.get({id: $routeParams.id}), CourseResource.query(), GroupResource.query()])
  .then(function(results){
     // results will be an array of values from resolved promises in the original order
   })
   .catch(function(err) {
     // will fail on any rejected promise
   });

答案 1 :(得分:1)

注入$ q服务,并以这种方式使用它:

$q.all(
  [
  CourseResource.query(),
  CurriculumResource.query(),
  GroupResource.query()
  ]
).then(function(response) {
  $scope.courses = response[0];
  $scope.curriculum = response[1];
  $scope.groups = response[2];
  // do what you need to do when all data is available
});

此外,您需要确保您的服务返回$ q延迟,$ http返回的所有请求都会延迟,以便您可以返回它们,但也许您想要将其包装起来处理结果(例如提取重要内容) info,o用模型逻辑预处理数据):

...
query: function() {
  return $http.get("...url...").then(function(response) {
    //process response here before return it
  }); // of course, the use of .then is optional
}
...