Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 以角度显示未定义的$scope_Javascript_Angularjs_Api - Fatal编程技术网

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
请求可能尚未返回,因此该项是
未定义的