Javascript 以角度显示未定义的$scope
这是我的密码Javascript 以角度显示未定义的$scope,javascript,angularjs,api,Javascript,Angularjs,Api,这是我的密码 var exchange = angular.module('app', []); exchange.controller('ExchangeController', ExchangeController); function ExchangeController($scope, $http) { $scope.items = []; $http .get(window.location.origin +
var exchange = angular.module('app', []);
exchange.controller('ExchangeController', ExchangeController);
function ExchangeController($scope, $http) {
$scope.items = [];
$http
.get(window.location.origin + "/api/get-item/", {
transformRequest: angular.identity,
headers: {'Content-Type': undefined, 'Process-Data': false}
})
.then(function(response){
$scope.items = response.data.items;
console.log($scope.items);
});
console.log($scope.items);
}
这里我的第一个控制台日志工作正常,但第二个显示未定义。为什么?第二个写入的
console.log($scope.items)代码>应将空数组记录到控制台。原因是$http.get
正在执行异步调用。这会导致然后
块的代码执行被延迟,直到http请求完成,并允许其余代码继续执行。如果这是您对异步代码的第一次介绍,我建议您回顾一下-参见一般用法。以及Javascript作为一个整体的承诺
也考虑了我在演示异步操作时为您所写的内容。p> 这是因为
$http
块正在异步运行。当调用到达您的console.log($scope.items)
时,http
请求可能尚未返回,因此该项是未定义的