2016-09-18 92 views
0

我正在写一个相当简单的crud应用程序,但是,我似乎被卡在编辑(编辑控制器)部分代码上。我有一个学生名单,我选择一个更新。但我得到错误“预期的响应包含一个对象,但有一个数组”。获取重复对象而不是单个对象的阵列

当我直接查询web服务,我得到 enter image description here

但是,当我检查元素,并转到网络选项卡上,我看到这个

enter image description here

这里是我的代码。

var StudentManagement = angular.module('StudentManagement',  ['ngRoute','ngResource','ui.bootstrap']); 

StudentManagement.config(function ($routeProvider) { 
    $routeProvider 
    .when("/", { 
     templateUrl: "list.html", 
     controller: "HomeController" 
    }) 
    .when("/add", { 
     templateUrl: "add.html", 
     controller: "AddController" 
    }) 
    .when("/edit/:editId", { 
     templateUrl: "edit.html", 
     controller: "EditController" 
    }) 
    .otherwise({ 
     redirectTo: "/" 
    }); 


    }); 

    StudentManagement.factory('Student', function ($resource) { 
    return $resource('/api/Student/:id', { id: '@id' }, { update: { method: 'PUT' } }); 
}); 

StudentManagement.controller("HomeController", 
function ($scope, $location, Student) { 

    $scope.search = function() { 
     $scope.students = Student.query(); 
    };// end search 

    $scope.reset = function() 
    { 
     $scope.search(); 
    }// end reset function 

    $scope.search(); 


    }); 

    StudentManagement.controller("EditController", 
    function ($scope, $location, $routeParams, Student) { 
    // get the student given the specific id 
    var id = $routeParams.editId; 
    $scope.student=Student.get({id: id}); 

    $scope.updateForm = function() { 
     Student.update({id:id}, $scope.student, function() { 
      $location.path('/'); 
     }); 
    }// end edit function 

    $scope.cancelForm = function() { 
     $location.path('/'); 
    }// end cancel function 


}); 
+0

如果你正在返回你的API中的数组,那么你应该使用IsArray的:在服务方法中为true。 – nikhil

+0

它不应该返回一个Array,这就是为什么我说当直接从浏览器调用Api时,它返回[{“id”:5,“firstname”:“somaya”,“lastname”:“幸福”,“年龄“:20,” studentId “:” 1A40000000" }]。有什么理由为什么在前端创建一个数组? – nahaelem

+0

它的一个数组......方括号表示一个数组..你明确地从服务器返回一个数组。 – nikhil

回答

0

您正在从服务器返回对象数组。

因此,您应该在资源定义中添加isArray : true

$resource('/api/Student/:id', { id: '@id' }, 
        { update: { method: 'PUT',isArray : true} 
      }); 

或者

可以从服务器

返回对象的对象,如果你想使当前代码可行

+0

Angular似乎不喜欢你的加法。编译失败。 – nahaelem

+0

oppps,纠正了这个问题,它应该在行动对象 –

+0

我想我已经想通了我的问题。如果有效的话会回复给你 – nahaelem

相关问题