从状态解析和控制器调用Restangular的区别

时间:2016-01-12 17:08:40

标签: angularjs restangular

我正在使用Restangular和angularJS。

以下是我的控制器代码。 我无法在控制台上打印教师输出,我无法使用vm.teacherList

案例1:

    angular.module("subjectManagement").controller('subjectTeacherAllocationCtrl',
         function ($scope, $state, $location, Restangular) {
             var vm = this;
             vm.teacherList = Restangular.all("teacher").getList().$object;
             console.log( " vm.teacherList ---> " + vm.teacherList);
     });

 console output is only  `vm.teacherList --->`

当我检查网络XHR时,我能够通过

等数据进行教师回复
[{teacherId: "3", empId: "9", teacherDateOfJoining: "2015-11-02", teacherJoiningGrade: "TGT",…},…]
0: {teacherId: "3", empId: "9", teacherDateOfJoining: "2015-11-02", teacherJoiningGrade: "TGT",…}
1: {teacherId: "4", empId: "10", teacherDateOfJoining: "2015-11-02", teacherJoiningGrade: "TGT",…}

案例2:  如果我将相同的代码行放在state resolve而不是controller中。我可以在控制台中打印vm.teacherList,我可以使用vm.teacherList执行任何操作。

.state('subjectTeacherAllocation', {
                        url: '/subject/subjectTeacherAllocation',
                        templateUrl: 'app/subject/edit/subjectTeacherAllocation.html',
                        controller: 'subjectTeacherAllocationCtrl as vm',
                        resolve: {

                            teacher: function (Restangular, $stateParams) {
                                return Restangular.all('teacher').getList();
                            }
                        }
                    })

  angular.module("subjectManagement").controller('subjectTeacherAllocationCtrl',
     function ($scope, $state, $location, teacher, Restangular) {
         var vm = this;
         $scope.teacher = {}
         vm.teacherList = teacher.plain();

         console.log( " vm.teacherList ---> " + vm.teacherList);

 });




console output is only  vm.teacherList --->  vm.teacherList ---> [object Object],[object Object],[object Object],[object Object],[object Object]

我想了解这两者之间的区别(案例1和案例2)  如何实现,在案例1中打印vm.teacherList,与案例2相同

1 个答案:

答案 0 :(得分:1)

<强>案例1

根据文档,getList。$ object返回对请求完成时数据将填充的空对象的引用。因此,如果您尝试立即打印数据,您将只看到该空对象。在开发人员控制台中检查网络对象时,您将看到已完成的请求,这就是您查看数据的原因。

案例2

由于您处于解析块中,因此在完成所有请求之前状态不会更改。因此,Restangular的调用必须在下一步之前完成。当您的控制器加载时,教师是一个完全填充的对象,您可以按预期使用数据。

使案例1像案例2一样工作

使用Restangular.all()。getList返回的promise,成功填充数据。

 vm.teacherList = {};
 Restangular.all('teacher').getList().then(function success(data) {
   vm.teacherList = data;
   console.log(vm.teacherList);
 });