0

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!

3 Answers 3

1

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
});
Sign up to request clarification or add additional context in comments.

3 Comments

What is the use of the 2nd parameter (headers ) in the function there ?
headers is a function that allows you to have access to the response headers, e.g. headers("Content-Type"). See docs.angularjs.org/api/ngResource/service/$resource#usage, section Returns.
Oh, that's nice. Thank you!
1

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

1 Comment

Thanks for this. Appreciated.
0

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.