2016-08-27 7 views
0

私のコントローラには、フォームの送信時に呼び出されるcreateListing()関数があります。 createListing()は、newListingServiceサービス内からsaveListing()関数を呼び出します。これによりデータベースへの$ http投稿要求が行われます。次に、コントローラにupdateListings()関数を使用して新しく作成されたリストを含めるために、ページに表示されたリストを更新する必要があります。私が抱えている問題は、createListing()でsaveListing()を呼び出す前にupdateListings()関数が呼び出されていることです。投稿のリクエストが完了した後にのみ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) { 
    }); 
    } 

} 

答えて

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 
    }) 
+0

完全に働いた、ありがとう! – useyourbrian

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; 

    } 
} 
関連する問題