繁体   English   中英

AngularJS服务函数未返回Promise

[英]AngularJS service function not returning promise

我对Angular并不陌生,所以如果你们需要更多信息,请告诉我,我将在这里添加。

我有一个控制器,该控制器对服务进行函数调用,该服务返回由HTTP.get函数检索的一些数据。 但是目前看来它没有返回任何数据或承诺。

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

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

调用的服务“后端”功能是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调用中接收到诺言或数据返回,或者两者都结合使用。

因此,我更大的问题是:如何对服务和服务功能进行编码,以便可以从不同的控制器调用它们并接收承诺/数据?

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

您忘记了调用该函数。 也不需要在工厂里面

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM