I recently started learning about Angular JS $http and $q services through a tutorial on Pluralsight. I focused on creating the eventData service to fetch JSON data from the server using promises, but encountered an issue when trying to assign the promise to $scope.event - it showed up as an empty object. I wondered why my original method didn't work.
After searching online for a solution, I came across a different code snippet that utilized the "then()" function on the promise to properly assign the result to $scope.event.
It struck me that the promise queue is typically meant to eliminate the need for passing callbacks, yet in this case, we are essentially passing a callback to the "then" function. This made me question if it defeats the purpose of having a promise queue in the first place.
// Event Data Function
eventsApp.factory("eventData", function($http, $q){
return {
events : function() {
var deferred = $q.defer();
$http({
method: "GET", url:"http://localhost/data/events/events.php"
})
.success(function(data,status,headers,config){
deferred.resolve(data);
})
.error(function(data,status,headers,config){
deferred.reject(status);
});
return deferred.promise;
}
}
});
// Original Event Controller
var eventController = eventsApp.controller('eventController',function($scope,eventData)
{
$scope.event = eventData.events()
});
// Revised Event Controller after research
var eventController = eventsApp.controller('eventController',function($scope,eventData)
{
eventData.events().then(function(result){
$scope.event = result
});
});