【发布时间】:2015-07-26 19:31:18
【问题描述】:
我是 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 调用的数据返回或两者的组合。
所以我的宏观问题是: 如何对我的服务和服务功能进行编码,以便我可以从不同的控制器调用它们并接收承诺/数据?
【问题讨论】:
-
由于您的
getRecentPosts是一种方法,您应该使用backend.getRecentPosts()而不是backend.getRecentPosts调用它,因为在第二种情况下,它会在后端对象上查找名为getRecentPosts的属性/字段它找不到,因此错误
标签: javascript angularjs http service controller