Reputation: 116
I have an HTTP request setup as a promise in a .factory and would like to send the result to a controller. However I am stuck with getting the data out of promise and into somewhere I can use it.
.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;
});
}();
})
and the .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;
});
},
Mo matter how I seem to try putting things into a scope I always seem to end up with the promise object. Can someone help me out?
Upvotes: 1
Views: 3555
Reputation: 538
The success or error method will always return a promise (it wraps your return value into a new promise). You shoudl set the value on the scope from within the success/error callback:
.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;
});
})
Upvotes: 1