你好我无法弄清楚如何返回正确的功能/部分服务,因为它因为Yammer API而有所作为。
我已经阅读了文档并尝试返回整个功能,但我花了很长时间才开始绝望,请帮助我。
我认为回报是在错误的地方 - 我收到了错误:
"Unable to get property 'then' of undefined or null reference"
我的控制器
app.controller("mainController", function($scope, $http, yammerREST) {
$scope.getYammerPosts = function () {
yammerREST.getYammerData($scope.yammerURL).then(function(data) {
$scope.results = data.results;
});
};
});
我的服务
app.service("yammerREST", function($http) {
this.getYammerData = function(url) {
var groupID = url.split("feedId=")[1];
console.log(groupID);
var baseURL = "https://www.yammer.com/api/v1/messages/in_group/" + groupID + ".json?threaded=true";
var url = baseURL;
var results = [];
getPosts();
function getPosts () {
return $http({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" }
}).then(function(response) {
results = results.concat(response.data.messages);
console.log(results);
if (response.data.meta.older_available == true) {
url = baseURL + "&older_than=" + results[results.length-1].id;
getPosts();
};
return {
yammerListName: response.data.meta.feed_name,
results: results,
};
}).catch(function(e){
console.log("Error: ", e);
});
};
};
});
答案 0 :(得分:2)
“无法获得财产'然后'未定义或空引用“
该错误消息通常意味着该函数未能return承诺:
app.service("yammerREST", function($http) {
this.getYammerData = function(url) {
var groupID = url.split("feedId=")[1];
console.log(groupID);
var baseURL = "https://www.yammer.com/api/v1/messages/in_group/" + groupID + ".json?threaded=true";
var startURL = baseURL;
var results = [];
//vvvv RETURN promise
return getPosts(baseURL,startURL);
function getPosts (baseURL, url) {
//vvvv RETURN promise
return $http({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" }
}).then(function(response) {
results = results.concat(response.data.messages);
console.log(results);
if (response.data.meta.older_available == true) {
var nextURL = baseURL + "&older_than=" + results[results.length-1].id;
//vvvv RETURN promise
return getPosts(baseURL,nextURL);
};
return {
yammerListName: response.data.meta.feed_name,
results: results,
};
}).catch(function(e){
console.log("Error: ", e);
//IMPORTANT to re-throw error
throw e;
});
};
};
});
递归调用getPosts
函数。要进行有效的递归,f(x)必须调用f(x + 1)直到满足某个结束条件。
同样在.catch
块中,re-throw errors对于跳过承诺链中的后续.then
块非常重要。