문제

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

도움이 되었습니까?

해결책

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
  });
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top