0

I am fairly new to Angular so if you guys need more information let me know and I'll add it up here.

I have a controller that makes a function call to a service that should return some data retrieved by an HTTP.get function. However currently it doesn't seem to return any data or promise.

Here is the controller code that calls and handles the data from the service

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 have also tried

backend.getRecentPosts.then(onRecentBlogPosts, onError);
//but then I get the error
TypeError: backend.getRecentProjects.then is not a function

The service 'backend' function that gets 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 look at the console (after the lines executed in the success function executes) I get

function getRecentPosts()
undefined

The goal here is to put all my http-related functions within the service then call it from different controllers. I am not sure if I should be receiving a promise or the data return from the http call or a combination of both.

So my bigger-picture question is: How do I go about coding my service & service functions so that I can call them from different controllers and receive a promise/data?

1
  • As your getRecentPosts is a method, you should invoke that using backend.getRecentPosts() instead of backend.getRecentPosts because in the second case, it looks for property/field named getRecentPosts on backend object which it could not find, hence the error Commented Jul 26, 2015 at 19:53

1 Answer 1

1
backend.getRecentPosts().then(onRecentBlogPosts, onError);

You forgot to call the function. Also no need to have then inside factory

var getRecentPosts = function() {
        return $http.get("http://example.com/blog")
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.