loganfarr
loganfarr

Reputation: 701

AngularJS service function not returning promise

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?

Upvotes: 0

Views: 727

Answers (1)

vinayakj
vinayakj

Reputation: 5681

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")
};

Upvotes: 1

Related Questions