Search code examples
javascriptangularjsrestangular

Restangular .getList() or get() not working when chained with .then() in controller, but works if resolved in routes


I want to be able to have exception handling when using getList() or get() however if I user then() nothing useful is returned. If remove then() then it returns what I'm expecting, but I don't have exception handling.

Restangular's own documentation uses then() with getList() so I'm not sure why it's not working.

Here's my controller code:

$scope.allSubjects = Restangular.all('subjects').getList().then(handleSuccess, handleError('Error getting all subjects'));

console.log($scope.allSubjects); // -> Promise {$$state: Object}

function handleSuccess(data) {
  return data;
}

function handleError(error) {
  return function() {
    $log.warn(error);
  };
}

However, if I resolve my data it works properly

.state('subjects', {
    url: '/subjects',
    templateUrl: 'components/subjects/list.html',
    controller: 'SubjectsListCtrl',
    controllerAs: 'vm',
    resolve: {
      getSubjectsResolve: function(Restangular) {
        return Restangular.all('subjects').getList().then(handleSuccess..., handleError...);
      }
    }
  })

I'm so lost! I don't get it.


Solution

  • In your handleSuccess, you are returning the data. Who are you returning it to? Typically, your success function would look like:

    function handleSuccess(response) {
        $scope.data = response.data;
    }