It's because $http.post
is an asynchronous method call. By the time your code gets to the console.log
call at runtime, the data from $http.post
may not have returned yet, therefore it would log the old value and not the new one.
If you want to console.log
the value after the post request has returned, you should move the console.log
statement to the then
block which will only run after the call has been returned.
function() {
var test = 0;
var url = 'http://test.php';
var user_id = 1;
$http.post(url,{user_id: user_id})
.then(function (response){
test = response.something;
console.log(test) // Move console.log inside promise then
})
}
If that does not work for you, it is because your call is likely failing for some reason or another. In this case, you can provide an additional function to handle the error.
function() {
var test = 0;
var url = 'http://test.php';
var user_id = 1;
$http.post(url,{user_id: user_id})
.then(function (response){
test = response.something;
console.log(test) // Move console.log inside promise then
}, function(err) {
test = err;
console.log(test)
});
}