[英]AngularJS console.log returns true data then empty object
I have a factory: 我有一家工厂:
app.factory("ExampleFactory", function() {
return {
map: {}
}
});
And controller: 和控制器:
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();
});
Why in the first case it returns an array but then returns nothing? 为什么在第一种情况下它返回一个数组却又什么都不返回?
UPDATE: Sorry, there was another problem and it was solved by me. 更新:对不起,还有另一个问题,这个问题我解决了。 I will not delete the answer because I received a correct solutions for this one.
我不会删除答案,因为我收到了正确的答案。
The first case that returns an array is actually executed second. 返回数组的第一种情况实际上是第二个执行的。 The program flow is as follows:
程序流程如下:
$scope.map
is set to an empty object by the factory. $scope.map
将$scope.map
设置为空对象。 $scope.init
is called $scope.init
被称为 $http.get
sends an http request to "/api" (but the request is not returned yet) $http.get
向“ / api”发送一个http请求(但该请求尚未返回) $scope.map
is printed to console.log
, still an empty object $scope.map
打印到console.log
,仍然是一个空对象 .success
function is called. .success
函数。 exampleMethod
sets $scope.map
to an array exampleMethod
设置$scope.map
到一个数组 $scope.map
is printed to console.log
, at which point it is an array $scope.map
打印到console.log
,这是一个数组 I think it should be retuning empty first in the console and then the array. 我认为应该先在控制台中将其调为空,然后在阵列中将其调为空。
This is because the callback that you are passing to the success method is executed asynchronously when the response from the GET /api
is received. 这是因为,当收到
GET /api
的响应时,异步执行要传递给成功方法的回调。 Let's explain it inside your code: 让我们在您的代码中进行解释:
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();
});
Does this makes sense to you? 这对您有意义吗?
Happy coding! 编码愉快!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.