如何在AngularJS中确保数据在使用之前先加载?

时间:2015-04-03 22:38:59

标签: javascript angularjs asynchronous anonymous-function

我猜这是一个经典的JavaScript和异步问题,但我没有得到,如何解决它。我正在使用AngularJS构建一个fronend。稍后将从API检索日期,但现在我只是从本地JSON文件中读取它。这是代码:

app.js

(function() {
    var app = angular.module('portfolio', []);

    app.controller('ProjectItemController', function() {
        this.projectItemData = dataProjectItem;
        console.log(dataProjectItem);
    });

    var dataProjectItem;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', config['base_url'] + '/dummy-data/project-item.json');
    xhr.onload = function() {
        dataProjectItem = JSON.parse(xhr.responseText);
    };
    xhr.send();

})();

list.phtml

<div id="projects" ng-app="portfolio">
    <div class="projectItem" ng-controller="ProjectItemController as projectItem">
        <div class="project-image"><img ng-src="{{projectItem.projectItemData._embedded.images[0].src}}" /></div>
    </div>
</div>

问题是,在服务器上(有时也在本地),数据尚未加载,脚本已经尝试使用projectItemData

我试图用匿名函数解决它,但它没有工作:

app.controller('ProjectItemController', function() {
    this.projectItemData = (function () {
        var dataProjectItem;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', config['base_url'] + '/dummy-data/project-item.json');
        xhr.onload = function() {
            dataProjectItem = JSON.parse(xhr.responseText);
        };
        xhr.send();
        return this.dataProjectItem;
    })();
});

(1)如何让脚本始终先加载数据然后再使用它?因为它目前正在AngularJS上下文中发生:(2)针对这个问题是否有特定的Angular解决方案?

修改

如何解决AngularJS中的这个问题?

1 个答案:

答案 0 :(得分:1)

是的,正如评论中提出的$http是在Angular中执行ajax请求的最简单方法。

如果您正在使用与之交互的RESTful后端,也可以使用ngResource

请查看下面的演示,并点击此处jsfiddle

显示$http服务的使用情况。

var app = angular.module('myApp', []);

app.factory('wikiService', function($http) {

  var wikiService = {
    getJSONP: function(country) {
      return $http.jsonp('http://es.wikipedia.org/w/api.php?titles=' + country.name.toLowerCase() + '&rawcontinue=true&action=query&format=json&prop=extracts&callback=JSON_CALLBACK');
    },
    post: function() {
      return $http.post('/echo/json/', {
        test: 'testdata',
        delay: 2
      });
    },
    get: function(url) {
      return $http.get(url);
    }
  };

  return wikiService;
});

app.controller('MainController', function($scope, wikiService) {

  wikiService.getJSONP({
    name: 'germany'
  }).then(function(data) {
    console.log(data);
    $scope.wikiData = data.data;
  });

  /*
  // commented here because of CORS
  wikiService.post().then(function(data) {
    console.log('posted', data);
  });

  wikiService.get('/echo/json/').then(function(data) {
    console.log('get data', data);
  }, function(reason) {
    console.log('Error: ', reason);
  });

  // the following request is not correct to show the error handler
  wikiService.get('/badurl').then(function(data) {
    console.log('get data', data);
  }, function(reason) {
    console.log('Error: ', reason.status == 404 ? 'page not found' : reason);
  });*/

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MainController">
    <div id="ng-error"></div>
    <pre ng-bind="wikiData | json"></pre>
  </div>
</div>