在 `.then` 方法之外未定义范围变量 [英] scope variable undefined outside `.then` method
问题描述
我在 if 语句中更改了作用域变量,在 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 服务 并在数据从服务器到达并且 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 承诺响应.
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*");
这篇关于在 `.then` 方法之外未定义范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!