【问题标题】:AngularJS console.log returns true data then empty objectAngularJS console.log 返回真实数据,然后返回空对象
【发布时间】:2015-11-24 06:49:13
【问题描述】:

我有一家工厂:

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();
});

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

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

【问题讨论】:

    标签: javascript angularjs scope angularjs-scope


    【解决方案1】:

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

    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,此时它是一个数组

    【讨论】:

    • 这是真的!我在浏览器中看到的第一个日志是一个空对象。但是我怎样才能实现我想要的呢?
    • 如果您在问题中提供有关您想要什么的更多信息,我可以看看如何做到这一点。
    【解决方案2】:

    我认为它应该首先在控制台中重新调整为空,然后再在数组中调整。

    这是因为当收到来自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();
    });
    

    这对你有意义吗?

    编码愉快!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多