AngularJS $资源成功和错误回调

时间:2015-10-01 08:19:26

标签: javascript angularjs

我在这里有一个简单的代码,但是我希望显示成功和错误回调。这是我的代码:

angular
    .module('studentInfoApp')
    .factory('Student', Student)
    .controller('StudentsController', StudentsController)
    .config(config);

function config($routeProvider) {
    $routeProvider
    .when('/', {
        controller: 'StudentsController',
        templateUrl: 'app/views/student-list.html'
    })
}

function Student($resource) {
    return $resource('/students');
}

function StudentsController(Student, $scope, $http) {

    Student.query(function(data) {
        $scope.students = data;
    });

}

正如您所看到的,function Student()只返回资源,但如果我使用.then,则无法获得成功和错误回调。我在这里错过了什么吗?谢谢!

3 个答案:

答案 0 :(得分:1)

这是一个解决方案:

Student.query(function(data, headers) {
  // OK
  $scope.students = data;
}, function(response) {
  // KO
});

另一个直接使用承诺:

Student.query().$promise.then(function(response) {
  // OK
  $scope.students = response.data;
}, function(response) {
  // KO
});

答案 1 :(得分:1)

使用angular $ resources时,您可以直接将查询保存到变量中。然后它将保留承诺,并在数据返回数据本身时。

如果您需要处理成功/错误,您可以使用保存的承诺并添加成功和错误回调,如下所示。

$scope.students = Student.query();
$scope.students.$promise.then( function(response) {
     console.log('success');
}, function (error) {
    console.log('error');
});

答案 2 :(得分:0)

管理让它工作,但如果有更好的方法,请随时发布它。这是我现在的代码:

function StudentsController(Student, $scope) {

    Student.query(function(data) {
        $scope.students = data;
    })
    .$promise.then(function successCallback(response) {
        console.log('success');
    }, function errorCallback(error) {
            console.log('error');
    });

}