2016-11-04 105 views
0

我是新來的角js。這裏我有代碼:我收到響應數據,如數字。在這段代碼中,我如何將響應數據分配爲$ scope.vote_counting。在這段代碼中不會返回任何東西。

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

請任何人都幫助到這一點。

回答

3

只需致電$http即可。它不必是一個函數

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

排序版本

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

注:您正在使用POST方法,但一個GET方法似乎在你的情況更合適(getVotes

0

$ http函數不返回服務器的響應。但是,正如你已經想出的那樣,你可以使用成功功能來獲得服務器響應。

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

最簡單的就是可能使用$http.post:簡單地設置在這樣成功的功能$scope.votes值。需要注意的是success是贊成不贊成的then

$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

噢,我沒有看到他在使用帖子...即使該網址是'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>