Reputation: 15307
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
Upvotes: 0
Views: 4469
Reputation: 10298
You are actually passing the return value of your functions to the promise.then
. you should pass a function. try this:
eventsApp.controller('EventController',
function EventController($scope, eventData) {
$scope.sortOrder = 'name';
eventData.getEvent().$promise.then(function (event) { successOnGetEvent(event); }, function (response) { errorOnGetEvent(response); });
function successOnGetEvent(event) {
$scope.event = event;
console.log(event);
};
function errorOnGetEvent(response) {
console.log(response)
};
});
What I did this is just add a wrapper anonymous function that runs the code you intended to run. This means the promise.then
will receive a function.
Upvotes: 2
Reputation: 37560
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);
Upvotes: 2