如何在服务异步调用完成后调用函数?

时间:2016-08-27 05:09:22

标签: angularjs asynchronous service

在我的控制器中,我有一个在提交表单时调用的createListing()函数。然后,createListing()从newListingService服务中调用saveListing()函数,该服务向数据库发出$ http post请求。然后,我需要更新页面上显示的列表,以使用控制器中的updateListings()函数包含新创建的列表。我遇到的问题是在createListing()中的saveListing()调用之前调用updateListings()函数。如何确保只在post请求完成后才调用updateListings()?

控制器:

 ...

  $scope.listings = {};

  $scope.updateListings = function(){
    $http.get('/listings')
       .then(function(res){
          $scope.listings = res.data;
        });
      };

   $scope.createListing = function(listingData){
     newListingService.saveListing(listingData);
     $scope.updateListings();
   };

newListingService:

function newListingService($http){
  this.saveListing = function(listingData){
    $http({
      method  : 'POST',
      url     : '/listings',
      data    : listingData
    })
    .success(function(data) {
    });
  }

}

2 个答案:

答案 0 :(得分:1)

@depiction是对的。你应该使用promises

但是,$http会自己回复承诺。因此,您不必使用$q或其他任何内容。只需返回请求,它就会返回promise

this.saveListing = function(listingData){
   return $http({
            method  : 'POST',
            url     : '/listings',
            data    : listingData
          });
}

并在您的控制器中:

newListingService.saveListing(listingData)
    .then(function(response){
        $scope.updateListings();
    }, function(err){
       // handle error here
    })

答案 1 :(得分:0)

你需要使用承诺。

function newListingService($http){
    this.saveListing = function(listingData){

    var deferred = $q.defer();

    $http({
      method  : 'POST',
      url     : '/listings',
      data    : listingData
    })
    .then(
        function success(data) {
            deferred.resolve(data);
        },
        function error(response) {
            deferred.resolve(false);
        }
    );

    return deferred.promise;

  }
}
相关问题