我将HTTP请求设置为.factory中的承诺,并希望将结果发送给控制器。但是我仍然坚持将数据从承诺中提取出来并进入我可以使用的地方。
.controller
.controller('MainCtrl', function ($scope, Main, User) {
$scope.feedResult = function () {
var feeds = [];
return Main.feed(key).success(function (data, status, headers, config) {
for (var i = 0; i < data.length; i += 1)
{
feeds.push(data[i]);
}
return feeds;
}).error(function (data, status, headers, config) {
console.log("This was an error back from the server");
console.log(data);
return data;
});
}();
})
和.factory
feed: function (token) {
return $http({
url: 'http://myserver.com/feed',
method: 'GET',
data: {
auth_code: token,
per_page: 10
}
}).success(function (data, status, headers, config) {
for (var i = 0; i < data.length; i += 1)
{
feeds.push(data[i]);
}
return feeds;
}).error(function (data, status, headers, config) {
console.log("This was an error back from the server");
console.log(data);
return data;
});
},
不管我怎么试着把东西放到一个范围内我似乎总是最终得到了promise对象。有人可以帮助我吗?
答案 0 :(得分:1)
成功或错误方法将始终返回一个promise(它将您的返回值包装到一个新的promise中)。您应该在成功/错误回调中设置范围上的值:
.controller('MainCtrl', function ($scope, Main, User) {
$scope.feedResult = [];
Main.feed(key).success(function (data, status, headers, config) {
for (var i = 0; i < data.length; i += 1)
{
$scope.feedResult.push(data[i]);
}
}).error(function (data, status, headers, config) {
console.log("This was an error back from the server");
console.log(data);
$scope.feedResult = data;
});
})