0

我正在使用 Parse 作为后端开发一个带有 Steroids/Supersonic 的应用程序,我正在努力使对象关系正常工作。这里举个例子。我有一对一关系的一门课程和一位老师(每门课程一位老师)。我想做的是与相关老师一起显示所有课程。为了在 Parse 中建立关系,我使用了指向另一个类的列类型“Pointer”。在控制器中的代码下方:

Course.findAll().then( function (courses) {
        $scope.$apply( function () {
          $scope.courses= courses;

          for (i = 0; i < $scope.courses.length; i++) {
          // look for the teacher
         Teacher.find($scope.courses[i].Teacher.objectId).then( function (teacher) {
            $scope.$apply( function () {
              $scope.courses[i].Teacher= teacher;
            }); 
          });   
          }
        });
      });

上述代码的问题是变量“i”未在 Teacher.find() 函数中定义,因此我无法将教师对象分配给正确的课程对象。我什至尝试在范围内使用特定变量来管理索引,就像在其他代码中一样:

Course.findAll().then( function (courses) {
        $scope.$apply( function () {
          $scope.courses= courses;
          $scope.index = 0
          for (i = 0; i < $scope.courses.length; i++) {
          // look for the teacher
         Teacher.find($scope.courses[i].Teacher.objectId).then( function (teacher) {
            $scope.$apply( function () {
              $scope.courses[$scope.index].Teacher= teacher;
              $scope.index = $scope.index + 1
            }); 
          });   
          }
        });
      });

第二个代码的问题是,老师随机链接到错误的课程可能是因为函数 find() 被异步调用,所以两个变量 i 和 index 并不总是同步。

我相信我面临的问题更多地与 angularjs 的异步行为有关,但我真的不知道如何解决它。谢谢你的帮助!

4

1 回答 1

0

我根本没有测试过这个,但是试着看看闭包,我可以想象这会起作用。

Course.findAll().then( function (courses) {
        $scope.$apply( function () {
          $scope.courses= courses;
          $scope.index = 0
          for (i = 0; i < $scope.courses.length; i++) {
              // look for the teacher
              var course = $scope.courses[i]; // to keep available in closure
         Teacher.find(course.Teacher.objectId).then( function (course, teacher) {
            $scope.$apply( function () {
              course.Teacher= teacher; // course should be available here, due to the closure

            }); 
          });   
          }
        });
      });
于 2015-11-02T13:10:04.840 回答