我是一个 Angular 新手,目前我在一个网站上工作,该网站将玩家的分数保存在 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 返回的 promise ,并像这样在 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);
});
});
});
});
});
关于javascript - $http.get 在执行 $http.post 后返回旧查询,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40962239/