2015-04-22 53 views
3

我想調用一個函數,該函數通過鏈接從servlet返回一個json對象。AngularJS和Servlet集成

我的HTML鏈接,請撥打FTEST功能:

<td><a href="" ng-controller="minaplantaCtrl" ng-click="fTest(x.id_camion_descarga)">ver</a></td> 

我的控制器:

app.controller('minaplantaCtrl', function($scope, $http, $window) { 
$scope.fTest = function(idDescarga){ 
     $http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga) 
     .success(function (response) {$scope.descargas = response.descargas;}); 
     $window.alert(JSON.stringify($scope.descargas)); 
    }; 
}); 

當我按下首次的鏈接出現在警報 「未定義」

但當我第二次按時,如果我能看到在警報中返回的json對象

當我按下第一個鏈接時可能會發生什麼?請幫助

感謝

回答

0

這裏的問題是你是在提醒$ scope.descargas因此它確實是沒有定義還沒有嘗試改變它像這樣的成功回調之外。

app.controller('minaplantaCtrl', function($scope, $http, $window) { 
$scope.fTest = function(idDescarga){ 
     $http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga) 
     .success(function (response) { 
     $scope.descargas = response.descargas; 
     $window.alert(JSON.stringify($scope.descargas)); 
     }); 
    }; 
}); 
0

因爲使用角$ HTTP每個服務器端請求是一個AJAX即異步調用服務器,你是假設你的警報方法的成功響應執行完成後調用。但這是錯誤的。

這就是承諾的概念來自Angular的地方。當您與服務器端的延遲執行該代碼

app.controller('minaplantaCtrl', function($scope, $http, $window) { 
    $scope.fTest = function(idDescarga) { 
     console.log("1"); 

     $http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga) 
     .success(function (response) { 
      $scope.descargas = response.descargas; 
      console.log("2"); 
     }); 

     console.log("3"); 
     $window.alert(JSON.stringify($scope.descargas)); 
    }; 
}); 

所以,你會看到控制檯日誌的順序爲:,和。

因此,您的成功功能是在從服務器接收到響應時執行的。因此,第一次,descargas變量中的值爲空,但get使用第一個服務器響應進行存儲,下一次顯示前一個調用的值。