Search code examples
javascriptangularjsresponseangular-promise

AngularJS Promise Response Undefined


I've read multiple articles on using $promise in AngularJS and I still can't figure out why I'm getting an error with my code below:

CONTROLLER CODE:

eventsApp.controller('EventController',
    function EventController($scope, eventData) {
        $scope.sortOrder = 'name';
        eventData.getEvent().$promise.then(successOnGetEvent(event), errorOnGetEvent(response));

        function successOnGetEvent(event) {
            $scope.event = event;
            console.log(event);
        };

        function errorOnGetEvent(response) {
            console.log(response)
        };
    });

SERVICE CODE:

eventsApp.factory('eventData', function($resource) {
    return {
        getEvent: function() {
            return $resource('/data/event/:id', {id:'@id'}).get({id:1});
        }
    }
});

In the Chrome console window, I get the error:

ReferenceError: response is not defined


Solution

  • In this line...

    eventData.getEvent().$promise.then(successOnGetEvent(event), errorOnGetEvent(response));
    

    successOnGetEvent and errorOnGetEvent are being executed right away. The error is because response (and event) aren't declared in this context. Try just passing the functions instead...

    eventData.getEvent().$promise.then(successOnGetEvent, errorOnGetEvent);