2016-11-04 7 views
0

私は角度jを初めて使用しています。ここに私はコードを持っています:私は番号のような応答データを受け取ります。このコードでは、どのように応答データを$ scope.vote_countingとして割り当てるのですか。このコードでは何も返されません。

$scope.votes = function(){ 
     var votes = $http({ 
       method: "post", 
       url: "/getVotes", 
       data: { id: $scope.Id} 
      }).success(function(response){ 
      }); 
      return votes; 
    } 

誰にも助けてください。

答えて

3

$httpと呼んでください。あなたはPOSTメソッドが、GETメソッドを使用している(getVotes)あなたのケースで、より適切なようだ:それはソートバージョンは

$http.post("/getVotes", { id: $scope.Id }).then(function(response) { 
    //handle success 
    $scope.votes_counting = response.data; 
}, function(error) { 
    //handle error 
}) 

注意される機能に

$http({ 
    method: "post", 
    url: "/getVotes", 
    data: { id: $scope.Id } 
}).then(function(response) { 
    //handle success 
    $scope.votes_counting = response.data; 
}, function(error){ 
    //handle error 
}); 

である必要はありません。

0

$ http関数は、サーバーの応答を返しません。しかし、すでに理解しているように、成功関数を使用してサーバーの応答を得ることができます。最も簡単にはおそらく$http.postを使用している

$http({ 
    method: "post", 
    url: "/getVotes", 
    data: { id: $scope.Id} 
}).success(function(response){ 
    $scope.votes = response 
}); 
0

:単にこのような成功関数の$scope.votes値を設定します。 successthenの非推奨されていることに注意してください:

$scope.retrieveVotes = function(){ 
    $http.post('/getVotes', {id : $scope.id}).then(function(response){ 
    $scope.votes = response.data; 
    }); 
} 

$http呼び出しがそうretrieveVotesも非同期で呼び出す非同期であることに注意してください。

+0

なぜ '$ http.post()'? – Weedoze

+0

@Weedoze '$ http({method: 'POST'、..)のショートカットでコードを読みやすく簡潔にする –

+0

ああ、私は彼が投稿を使っているのを見ていませんでした... URLは 'getVotes'です – Weedoze

1

約束事の基本的な取り扱いを示すスニペットを追加しました。ここでは、httpコールをモックするサービスを使用しました。応答はスコープ変数に添付され、ビューに表示されます。

angular.module('TestApp', []) 
 
    .factory('MockHttp', function($q) { 
 
    return { 
 
     getMockData: function() { 
 
     return $q.when(['A', 'B', 'C']); 
 
     } 
 
    }; 
 
    }) 
 
    .controller('TestController', function($scope, MockHttp) { 
 
    $scope.res = null; 
 

 
    MockHttp.getMockData() 
 
     .then(function(res)  { 
 
     $scope.res = res; 
 
     }) 
 
     .catch(function(err) { 
 
     console.log(err); 
 
     }); 
 

 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="TestApp"> 
 
    <div ng-controller="TestController"> 
 
    {{res}} 
 
    </div> 
 
</div>

関連する問題