I'm still getting the hang of Angular so if you need more information, just let me know and I'll update it here.
So I have a controller that's supposed to call a function from a service which should return some data fetched through an HTTP.get request. However, at the moment, it's not returning any data or promise.
Here's the controller code that's making the call to the service and handling the data:
var onRecentBlogPosts = function(data) {
$scope.recentBlogPosts = data;
$log.info($scope.recentBlogPosts);
$log.info(JSON.stringify($scope.recentBlogPosts));
}
var onError = function(response) {
$('.error-container').html("<div class='messages error'>Could not fetch the data. <br /><br />More information: <br />"+response+"</div>");
}
$q.when(backend.getRecentPosts).then(onRecentBlogPosts, onError);
I also tried:
backend.getRecentPosts.then(onRecentBlogPosts, onError);
//but then I get the error
TypeError: backend.getRecentProjects.then is not a function
The function in the 'backend' service being called is getRecentPosts
Service code:
(function() {
var backend = function($http, $q) {
var getRecentPosts = function() {
return $http.get("http://example.com/blog")
.then(function(response) {
return response.data;
});
};
return {
getRecentPosts: getRecentPosts
};
};
var module = angular.module("moduleName");
module.factory("backend", backend);
}());
When I check the console (after the lines executed in the success function), I see:
function getRecentPosts()
undefined
My main question is how do I structure my service and service functions to be able to call them from various controllers and receive both a promise and data?