2016-12-04 38 views
1

我是一个有角度的新手,现在我正在一个网站上工作,在将一个postgres数据库中的玩家比分保存在一个网站之前,在插入表格“Puntaje”之前,我必须保存游戏ID和ID播放器到另一个表中,我的代码实际上是这样做的,但是当我试图检索这个表中最后插入的ID时,它会返回一个查询,就好像它没有插入密钥一样,尽管在数据库中它显示它已插入,这里是代码:

angular.module('clienteJuegoApp').controller('Juego1Ctrl', function ($scope, $http){ 
$scope.juego = "Survive"; 
$scope.add = function(){ 

    //First part, saves the gameID and the Player ID into the 1st table 
    console.log($http.get('http://127.0.0.1:8080/v1/jugador').then(function(response) { 
    console.log($scope.d = response.data); 
    console.log("long"+$scope.d.length); 
    console.log("idjugaor"+$scope.d[$scope.d.length-1].Id); 
    var datosJuegoJugador={ 
     idjuego: {Id:1}, 
     idjugaor:{Id:$scope.d[$scope.d.length-1].Id} 
    }; 
    $http.post("http://127.0.0.1:8080/v1/juegojugador", datosJuegoJugador); 
    console.log("se inserto"); 


    //Second part, retrieve the last inserted Id of the previous table 

    console.log($http.get('http://127.0.0.1:8080/v1/juegojugador').then(function(response2) { 
    console.log($scope.dj = response2.data) 
    console.log("idjuegojugador:"+$scope.dj[$scope.dj.length-1].Id) 

    var data = { 
     Idjuegojugador: {Id: $scope.dj[$scope.dj.length-1].Id}, 
     Puntaje: parseInt($("input:text[name=puntaje]").val()) 
    }; 

    console.log(data) 
    $http.post("http://127.0.0.1:8080/v1/puntaje", data); 
    })) 
}))} 

为什么会发生?我该如何解决它? 在此先感谢。

回答

1

由于您正在制作多个异步请求取决于彼此的结果,您需要确保每个请求都已完成,然后再转到下一个请求。

要做到这一点,你可以使用$ HTTP回报的承诺,并在随后的回调函数,因为这

angular.module('clienteJuegoApp').controller('Juego1Ctrl', function ($scope, $http){ 
    $scope.juego = "Survive"; 
    $scope.add = function(){ 

     $http.get('http://127.0.0.1:8080/v1/jugador') 
      .then(function(response) { 
       $scope.d = response.data); 
       var datosJuegoJugador={ 
        idjuego: {Id:1}, 
        idjugaor:{Id:$scope.d[$scope.d.length-1].Id} 
       }; 

       $http.post("http://127.0.0.1:8080/v1/juegojugador", datosJuegoJugador).then(function(response2) { 

        $http.get('http://127.0.0.1:8080/v1/juegojugador').then(function(response3) { 
         $scope.dj = response3.data 
         var data = { 
          Idjuegojugador: {Id: $scope.dj[$scope.dj.length-1].Id}, 
          Puntaje: parseInt($("input:text[name=puntaje]").val()) 
         }; 
         $http.post("http://127.0.0.1:8080/v1/puntaje", data); 
        }); 
       }); 
     }); 
    }); 

}); 
+0

非常感谢,它就像一个魅力! –

+0

太棒了:-)祝你有美好的一天 –

1

$http.post$http.get是异步的。你需要在帖子完成后调用get。邮政和内部回拨呼叫获得后使用then

+0

它没有工作......你能解释更多内容,请加视电话? –