当我记录id时,它会显示正确的id。我想在第二个url中传递此id并相应地获取数据。
就像当id为9时,当我把它放在这个url: &room_type=9&day=1
时,它可以工作,但不是我用这种方式url: '&room_type=' +$scope.id + '&day=1'
$http({
method:'GET',
url: '&hotel_id=' +$scope.current_Hotel.hotel_id
}).then(function(response){
var roomdata = response.data;
$scope.roomdata = roomdata;
var roomtype = roomdata.data;
angular.forEach(roomtype, function(value, key){
var id = value.room_type_id;
$scope.id = id;
console.info(id);
});
});
$http({
method:'GET',
url: '&room_type=' +$scope.id + '&day=1'
}).then(function(response){
var plan = response.data;
$scope.plan = plan;
});
答案 0 :(得分:2)
这是因为异步编程在javascript中的工作方式。在您的代码中,您将这两个http调用重新调用,并且定义的回调(然后)在您获得结果之后才会触发。因此,在第二次http调用被触发时,不会填充id
。如果你想用id
来调用它,并且在第一个呼叫的回调中定义了id
,那么你必须从你第一个http呼叫的回调中调用它,而不是在它之后。
以下是如何处理它
$http({
method:'GET',
url: '&hotel_id=' +$scope.current_Hotel.hotel_id
}).then(function(response){
var roomdata = response.data;
$scope.roomdata = roomdata;
var roomtype = roomdata.data;
angular.forEach(roomtype, function(value, key){
var id = value.room_type_id;
$scope.id = id;
console.info(id);
});
// call http now that id is defined
$http({
method:'GET',
url: '&room_type=' +$scope.id + '&day=1'
}).then(function(response2){
var plan = response2.data;
$scope.plan = plan;
});
});
答案 1 :(得分:2)
Http请求您使异步工作,使用promise chain在另一个之后调用请求
function getHotelId(){
return $http({
method:'GET',
url: '&hotel_id=' +$scope.current_Hotel.hotel_id
})
}
function getPlan(){
return $http({
method:'GET',
url: '&room_type=' +$scope.id + '&day=1',
})
}
$scope.processform = function() {
getHotelId()
.then( function( response )
{
var roomdata = response.data;
$scope.roomdata = roomdata;
var roomtype = roomdata.data;
angular.forEach(roomtype, function(value, key){
var id = value.room_type_id;
$scope.id = id;
console.info(id);
});
return getPlan();
})
.then(function(response){
console.log(response.data);
})
}