范围变量undefined在.then`方法之外 [英] scope variable undefined outside `.then` method
问题描述
我在if语句中更改了scope变量,在if语句之外更改了一个未定义的变量
I changed the scope variable in an if statement and outside the if statement it turned into an undefined variable
app.controller("Login", function($scope, $window,$http){
var status;
$scope.loginUser = function(logData){
$http.post('/corporate/login',logData).then(function(response){
var data = response.data
var status = data.success;
if(status == true){
$scope.logStatus = true;
console.log($scope.logStatus); // prints true
}else{
$scope.logStatus = false;
}
})
console.log($scope.logStatus); //prints undefined
}
});
推荐答案
外...它变成了一个未定义的变量
outside ... it turned into an undefined variable
它没有变成 undefined
价值。代码中的最后一个 console.log
在成功处理程序中的 console.log之前执行。它是 undefined
,因为它尚未由成功处理程序设置。
It did not "turn into" an undefined
value. The last console.log
in the code executes before the console.log in the success handler. It is undefined
because it has not yet been set by the success handler.
console.log("Part1");
console.log("Part2");
var promise = $http.get(url);
promise.then(function successHandler(response){
console.log("Part3");
});
console.log("Part4");
Part4的控制台日志不必等待数据从服务器返回。它在XHR 启动后立即执行。 Part3的控制台日志位于成功处理函数内,该函数由 $ q service 并在数据从服务器到达并且XHR 完成之后调用。
The console log for "Part4" doesn't have to wait for the data to come back from the server. It executes immediately after the XHR starts. The console log for "Part3" is inside a success handler function that is held by the $q service and invoked after data has arrived from the server and the XHR completes.
有关详细信息,请参阅如何在成功处理程序外使用$ http promise响应。
For more information, see How to use $http promise response outside success handler.
console.log("Part 1");
console.log("Part 2");
var promise = new Promise(r=>r());
promise.then(function() {
console.log("Part 3");
});
console.log("Part *4*");
这篇关于范围变量undefined在.then`方法之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!