访问promise的元素,它们是对象而不是简单类型

时间:2014-07-30 20:00:45

标签: angularjs object promise

我有一项研究,它有多个案例和多个executionMessages。每个案例都有多个executionSteps。我能够访问研究,案例甚至每个案例的executionSteps。我无法弄清楚为什么我无法访问完整的executionMessages。我的意思是每个executionMessage都有一个类型,消息可以访问,但executionMessage中的任何对象都没有访问。这是代码

        StudyService.studies.get({id: $routeParams.studyIdentifier}).$promise.then(function(study) {
                  $scope.study = study;
                  StudyService.executionMessagesForStudy.get({id: study.id}).$promise.then(function(executionMessages){
                      $scope.study.executionMessages = executionMessages;
                  });
                  for(var i=0;i<study.cases.length;i++){
                      var callback = callbackCreator(i);
                      StudyService.executionstepsForCase.get({id: $routeParams.studyIdentifier,caseId:study.cases[i].id})
                      .$promise.then(callback);
                  }
            });
    function callbackCreator(i) {
          return function(executionSteps) {
            $scope.study.cases[i].executionSteps = executionSteps;
          }
    }

1 个答案:

答案 0 :(得分:0)

您的服务类型似乎正在使用$resource(猜测您正在使用的.get().$promise模式),来自文档:

  

...调用$ resource对象方法会立即返回一个空引用(对象或数组,具体取决于isArray)。从服务器返回数据后,将使用实际数据填充现有引用。这是一个有用的技巧,因为通常将资源分配给模型,然后由视图呈现。

请参阅:https://docs.angularjs.org/api/ngResource/service/ $ resource

所以你的代码可以像这样简化:

// get() returns an object that will "fill-in" with the attributes when promise is resolved
$scope.study = StudyService.studies.get({id: $routeParams.studyIdentifier})

$scope.study.$promise.then(function(study) {
     // again, executionMessages gets a placeholder that will be filled in on the resolved promise
     $scope.study.executionMessages = StudyService.executionMessagesForStudy.get({id: study.id});

     angular.forEach(study.cases, function(case, idx) {
        // again, executionSteps is a placeholder that will be filled in on the resolved promise
        var executionSteps =  StudyService.executionstepsForCase.get({id: $routeParams.studyIdentifier, caseId: case.id})
        // not sure if ordering is important, the service calls can return in any order
        // so using push can produce list with elements in any order.
        $scope.study.cases.push(executionSteps);
     });
 });

在第一次服务调用解析后,您仍然需要使用study.$promise来获取嵌套数据。