Reputation: 13452
I have a simple code here that works however I wanted to display the success and error callbacks. This is my code:
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;
});
}
As you can see the function Student()
just returns the resource but I can't get the success and error callback if I use the .then
for example. Am I missing something here? Thank you!
Upvotes: 0
Views: 1707
Reputation: 541
When using angular $resources you can just save the query directly to your variable. It will then hold the promise and when data returns the data itself.
If you need to handle success/error you can just use the saved promise and add success and error callbacks like below.
$scope.students = Student.query();
$scope.students.$promise.then( function(response) {
console.log('success');
}, function (error) {
console.log('error');
});
Upvotes: 1
Reputation: 48827
Here is a solution:
Student.query(function(data, headers) {
// OK
$scope.students = data;
}, function(response) {
// KO
});
Another one using the promise directly:
Student.query().$promise.then(function(response) {
// OK
$scope.students = response.data;
}, function(response) {
// KO
});
Upvotes: 1
Reputation: 13452
Managed to get it working, but if there are better ways to do it please feel free to post it also. This is my code now:
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');
});
}
Upvotes: 0