Integration with AngularJS and Servlet

I am trying to call a function that returns me a json object from a servlet by reference.

My HTML link, fTest function call:

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

      

My controller:

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));
     };
});

      

when i click the first time the link appears undefined "

but when i click a second time if i see the json object that is returned in the message

What can happen when I click the first link? please, help

thank

+3


source to share


2 answers


The problem is that you are warning $ scope.descargas outside of the success callback, so it really isn't defined, but try changing it like this.



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


source


Since every server-side request using $ http in Angular is AJAX, that is, an asynchronous call to the server, you assume that your notifier method will be called after the success response has completed. But this is wrong.

This is where the concept of promises comes in 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));
     };
});

      



So when you execute this code with a server side delay, you will see the console logging order as 1 , 3, and 2 .

So your success function is executed when the response is received from the server. Therefore, the first time the variable descargas

is null, but it is stored using the response from the first server, and the next time it displays the value from the previous call.

0


source







All Articles