[英]How to ensure in AngularJS, that the data is loaded first before it is used?
I guess it's a classic JavaScript and asynchronism issue, but I didn't get, how to solve it. 我猜这是一个经典的JavaScript和异步问题,但我不知道如何解决它。 I'm building a fronend with AngularJS.
我正在用AngularJS建立朋友。 Later the date will be retrieved from an API, but now I'm simply read it from a local
JSON
file. 稍后将通过API检索日期,但是现在我只是从本地
JSON
文件中读取日期。 Here is the code: 这是代码:
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>
The problem is, that on the server (and sometimes locally as well), the data has not yet been loaded and script is already trying to use projectItemData
. 问题是,在服务器上(有时甚至在本地),数据尚未加载,脚本已经尝试使用
projectItemData
。
I've tried to solve it with a anonymous function, but it hasn't worked: 我试图用匿名函数来解决它,但是没有用:
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) How to make the script always load the data first and only then use it? (1)如何使脚本始终先加载数据,然后才使用它? And since it's currently taking place in the AngularJS context: (2) Is there a specific Angular solution for this problem? 并且由于它当前是在AngularJS上下文中进行的:(2)对于此问题是否有特定的Angular解决方案?
EDIT 编辑
How to solve this problem in AngularJS? 如何在AngularJS中解决这个问题?
Yes, as proposed in the comments $http is the easiest way to do ajax requests in Angular. 是的,正如评论中所建议的$ http是在Angular中执行ajax请求的最简单方法。
You could also use ngResource if you're having a RESTful backend that you're interacting with. 如果您要与之交互的RESTful后端,也可以使用ngResource 。
Please have a look at the demo below and here at jsfiddle . 请看下面的演示,这里是jsfiddle 。
It shows the usage of $http
service. 它显示了
$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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.