Reputation: 191
I have started using Restangular for my AngularJS project and want to create a service using Restangular to make REST calls. The service would have a function like this:
getAll
$scope.account = save($scope.account)
$scope.account = update(account)
Now since a Restangular call returns a promise inside the service which would have to be called like then() to get the results, how do I return the fetched or updated result from my service wrapper?
I want to create a wrapper API so that I can have any other business logic after I fetch the record and then return back the result from my service API. I can use the Restangular service directly in my controller but I need a proper service layer to be called from controller which would return me the result of the REST call and not just a promise.
Jay
Upvotes: 2
Views: 460
Reputation: 9108
You would need to make use of promise chaining.
So in your service you would have (notice we are returning the promise):
this.save = function(newAccount) {
..... // Do business logic on account before submit
return restangular.all('accounts').post(newAccount).then(function(result){
...... // Do business logic after successful save
return newAccount;
}, function(error){
...... // Do business logic on error
});
};
And then inside your controller:
$scope.saveAccount = function(newAccount) {
service.save(newAccount).then(function(savedAccount){
$scope.account = savedAccount;
}, function(errror) {
..... // Error handling
});
};
Upvotes: 1