【问题标题】:Angular.js wait for multiple resource (ajax) callsAngular.js 等待多个资源(ajax)调用
【发布时间】:2014-09-16 00:03:48
【问题描述】:

我有一个 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!'

【问题讨论】:

    标签: javascript angularjs coffeescript


    【解决方案1】:

    我相信你可以通过$q.all 来实现这一点,假设你所有的请求都返回了 Promise。类似的东西

    $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
       });
    

    【讨论】:

    • 我正在使用它,课程和小组返回正常,但课程结果 (results[0]) 仍然是未解决的响应。我不确定为什么。这个控制器所在的页面上的表单很好地显示了课程数据,因此承诺确实得到了解决。我只是使用具有默认设置的 $resource 模块。我的 CurriculumResource 中唯一真正设置的是 url。
    【解决方案2】:

    注入$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
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 2018-11-08
      相关资源
      最近更新 更多