angularjs ngResource成功未定义

时间:2015-05-20 10:57:07

标签: javascript angularjs ngresource

我有一个像这样的ngResource工厂:

app.service 'Api', ['$resource', ($resource) ->
    {
        Student: $resource "/api/v1/students/:id", {id: "@id", option: "@option"}, { 'update': {method: 'PUT'}}
]

我有一个像这样的控制器:

app.controller 'newStudentCtrl', ($scope, $state, Api) ->

    $scope.addNewStudent = ->
        student = Api.Student.save(
            student: $scope.newStudent
            )
        console.log(student.id)
        $state.go('student.new', { id: student.id})

保存新的学生记录,但student.id返回未定义。

console.log(student)返回以下内容:

Resource {student: Object, $promise: Promise, $resolved: false....
$promise: Promise
$resolved: true
id: 88
last_name: "Baggins"

如何处理成功回调才能获得student.id?

1 个答案:

答案 0 :(得分:0)

这对我有用:

$scope.addNewStudent = -> 
Api.Student.save { student: $scope.newStudent}, ((successResponse, headers) ->
    console.log successResponse.id
     ....

这里给出了解决方案:

handle error callback on save() method $ngResource