简体   繁体   English

使用AngularJS加载和使用数据

[英]loading and using data with AngularJS

I'd like to understand the logic of it, so I just post some generic code: 我想了解它的逻辑,所以我只发布一些通用代码:

1) I get the data from a JSON file with the service "loadData": 1)我使用服务“ loadData”从JSON文件中获取数据:

return {
        myData: function(){
           return $http.get(path + "data.json");
        }
}

2) In the main controller: 2)在主控制器中:

loadData.myData().then(function(result){
      $scope.vm.myData = result.data;
});

then, wherever I look for that with: 然后,无论我在哪里寻找它,都可以:

console.log($scope.vm)

I have the all object with the data inside, instead, if I look for: 如果我在寻找,我将所有对象都与数据一起放在里面:

console.log($scope.vm.myData)

I have always "undefined", and also I cannot use it in any function (the only way is to look for it inside the function above). 我总是“未定义”,而且我也不能在任何函数中使用它(唯一的方法是在上面的函数中查找它)。 What I'd like to have is just to get some data at the begin and then use it wherever I need it. 我想要的只是在开始时获取一些数据,然后在需要的地方使用它。

If your code looks something like this, then the second console statement is firing before the asynchronous call comes back (ie before the promise resolves). 如果您的代码看起来像这样,那么第二个控制台语句将在异步调用返回之前(即,在Promise解决之前)触发。

loadData.myData()
   .then(function(result) {
      $scope.vm.myData = result.data;
      console.log(1, $scope.vm);  // Runs when the promise resolves
   });
console.log(2, $scope.vm);  // Runs once the data is requested (no guarantee the promise has resolved yet).

As a result, any work that needs access to the data returned from the call must be put inside the then function, otherwise you have no guarantee that the data is available. 结果,任何需要访问从调用返回的数据的工作都必须放在then函数中,否则您不能保证数据可用。

The output above is: 上面的输出是:

2 undefined
1 [your data object]

For more information on promises and asynchronous calls in Angular, this is a fantastic resource, and comes with cartoons! 有关Angular中的Promise和异步调用的更多信息,这是一个很棒的资源,并且附带卡通! http://andyshora.com/promises-angularjs-explained-as-cartoon.html http://andyshora.com/promises-angularjs-explained-as-cartoon.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM