AngularJS console.log返回真数据,然后返回空对象

AngularJS console.log returns true data then empty object

本文关键字:返回 然后 对象 console log AngularJS 数据      更新时间:2023-09-26

我有一个工厂:

app.factory("ExampleFactory", function() {
    return {
        map: {}
    }
});

和控制器:

app.controller("appCtrl", function($scope, $http, ExampleFactory) {
    $scope.map = ExampleFactory.map;
    $scope.init = function() {
        $http.get("/api") //success
            .success(function(result) {
                $scope.map = exampleMethod(result);
                console.log($scope.map); //{ "1": Object, "2": Object }
            });
        console.log($scope.map); //Object {}
    };
    $scope.init();
});

为什么在第一种情况下,它返回一个数组,但然后什么也不返回?

更新:对不起,还有一个问题,我已经解决了。我不会删除答案,因为我收到了正确的答案。

返回数组的第一个例子实际上是第二个执行的。程序流程如下:

  1. $scope.map被工厂设置为空对象。
  2. $scope.init称为
  3. $http.get向"/api"发送http请求(但请求尚未返回)
  4. $scope.map打印为console.log,仍然是空对象
  5. 在此之后的某个时刻,web服务器返回您的http请求,此时调用.success函数。
  6. exampleMethod设置$scope.map为数组
  7. $scope.map被打印到console.log,此时它是一个数组

我认为它应该首先在控制台上返回空,然后返回数组。

这是因为当收到来自GET /api的响应时,您传递给成功方法的回调是异步执行的。让我们在代码中解释一下:

app.controller("appCtrl", function($scope, $http, ExampleFactory) {
    $scope.map = ExampleFactory.map;
    $scope.init = function() {
        // Get request to the /api
        $http.get("/api") //success
            // here we instruct it to use our function if success 
            // but it is not executed until the response is received.
            .success(
                // Callback that is executed on success HTTP 200
                function(result) {
                     $scope.map = exampleMethod(result);
                     // Second console.log displayed after receiving 
                     // the response to the $http.get call
                     console.log($scope.map); //{ "1": Object, "2": Object }
                }
                /////////////////////////////////////////////////
                );
        // First console.log will display empty object
        console.log($scope.map); //Object {}
    };
    $scope.init();
});

这对你有意义吗?

编码快乐!