AngularJS $resource成功和错误回调
AngularJS $resource success and error callback
我这里有一个简单的代码,但是我想显示成功和错误回调。这是我的代码:
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');
});
}
相关文章:
- 测试Angular Service解决错误回调中的promise
- $http服务未触发成功或错误回调
- jQuery AJAX错误回调未运行
- JavaScriptajax请求servlet调用错误回调函数
- 为什么 AJAX 完成和错误回调都触发了
- Cordova Android短信插件不会触发成功或错误回调
- 无法识别错误回调
- 在第一次错误回调时退出承诺链
- 如何获取 Ember 组件对象内部承诺成功或错误回调
- 在 Node.js 中传播错误回调,并避免所有额外的麻烦
- 在 HTTP 错误回调中访问“this”
- 在 AngularJS 中声明一个承诺,并带有命名的成功/错误回调
- 谷歌浏览器中的地理位置错误回调
- PhoneGap 3.0.0 Tanelih 蓝牙插件在 Android 上已启用错误回调不起作用
- $http错误回调不能与 httpProvider responseInterceptor 结合使用
- JayData 上的默认错误回调
- 错误回调中的错误:TestPlugin2 = 引用错误:找不到变量:在 file:///android_asset/ww
- 主干.js:保存方法始终返回错误回调
- AJAX 中的成功或错误回调不起作用
- Backbone.js:奇怪的.save()错误回调