AngularJS $resource成功和错误回调

AngularJS $resource success and error callback

本文关键字:错误 回调 成功 resource AngularJS      更新时间:2023-09-26

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

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为例。我遗漏了什么吗?谢谢你!

解决方案:

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

另一个直接使用promise的例子:

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

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

如果你需要处理成功/错误,你可以使用保存的承诺,并像下面这样添加成功和错误回调。

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

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

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');
    });
}