繁体   English   中英

$ http.get在执行$ http.post之后返​​回旧查询,我在做什么错?

[英]$http.get returning an old query after doing $http.post, what am i doing wrong?

我是新手,目前正在网站上,将球员的得分保存在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);
    }))
}))}

为什么会发生? 我该如何解决? 提前致谢。

$http.post$http.get是异步的。 发布结束后,您需要致电get。 在post和内部回调调用get之后使用then

当您发出多个异步请求时,这些请求取决于彼此的结果,因此您需要确保每个请求都已完成,然后再继续下一个请求。

为此,您可以使用$ http返回的承诺,并在then回调函数中添加依赖调用,如下所示

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

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM