AngularJS 服务功能不返回承诺

AngularJS service function not returning promise

我是 Angular 的新手,所以如果你们需要更多信息,请告诉我,我会在此处添加。

我有一个控制器,它对服务进行函数调用,应该 return HTTP.get 函数检索一些数据。然而,目前它似乎 return 没有任何数据或承诺。

这是调用和处理来自服务的数据的控制器代码

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

我也试过了

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

调用的服务 'backend' 函数是 getRecentPosts

服务代码:

(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);

}());

当我查看控制台时(在成功函数中执行的行执行之后)我得到

function getRecentPosts()
undefined

这里的目标是将我所有与 http 相关的功能放在服务中,然后从不同的控制器调用它。我不确定我是否应该从 http 调用或两者的组合中收到承诺或数据 return。

所以我的大问题是: 我该如何编写我的服务和服务功能,以便我可以从不同的控制器调用它们并接收 promise/data?

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

您忘记调用函数了。也不需要在 factory

里面
var getRecentPosts = function() {
        return $http.get("http://example.com/blog")
};