我猜这是一个经典的 JavaScript 和异步问题,但我不明白,如何解决它。我正在用 AngularJS 构建一个前端。稍后将从 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 中解决这个问题?
最佳答案
是的,按照评论中的建议 $http是在 Angular 中执行 ajax 请求的最简单方法。
您还可以使用 ngResource如果您有与之交互的 RESTful 后端。
请查看下面的演示以及此处的 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>
关于javascript - 在 AngularJS 中如何确保数据在使用之前先加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29440620/