Reputation:
//inside a service PService
this.getPTypes = function(){
var types = PTypesFactory.get({});
return types.$promise.then(function(result)
{
console.log(result.groups);
return result.groups;
});
}
//inside a controller
$scope.groups = PService.getPTypes();
console log shows correct fetched REST data, but when I do
console.log($scope.groups);
I get
Object {then: function, catch: function, finally: function}
which is promise API instead of the correct resolved data.
Upvotes: 1
Views: 81
Reputation: 32357
The problem is that you trying to use a asynchronous function like it was a synchronous one.
then
is a method which returns a promise.
when invoking it with a callback that callback would not be invoked immediately, only when the response get back from the server.
Service
this.getPTypes = function(callback){
PTypesFactory.get({}).then(callback);
}
Controller
PService.getPTypes(function(res){
$scope.groups = res.data;
});
Upvotes: 1
Reputation: 165951
Promises are used to handle asynchronous operations. The function you pass to the then
method is called at some indeterminable point in time. You can't return a value from within it to some other point in execution.
Instead of calling then
in your service, just return the promise:
this.getPTypes = function(){
return PTypesFactory.get({}).$promise;
}
and handle its resolution in the controller:
$scope.groups = PService.getPTypes().then(function(result) {
console.log(result.groups);
});
Upvotes: 0