简体   繁体   English

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

[英]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.

相关问题 CheerioCrawler:如何在提取数据之前确保页面已完全加载? - CheerioCrawler: How do I ensure a page is fully loaded before extracting the data? 在页面加载之前加载数据AngularJS和NodeJS - Load data before page is loaded AngularJS and NodeJS AngularJS承诺在加载数据之前得到解决 - AngularJS promise is resolved before data is loaded 如何在调用javascript文件之前确保页面已加载 - How to ensure page loaded before calling javascript file 如何在PageLoad上添加类之前确保元素已加载 - How to Ensure Elements have Loaded Before Adding Class on PageLoad 如何确保页面加载jQuery时加载第一张幻灯片? - How to ensure that the first slide is loaded when the page loads jQuery? 如何在查看angularjs之前确保范围变量已更新和绑定 - How to ensure that a scope variable updates and binds before going to view angularjs angularJS中的$ broadcast计时问题,如何确保在广播之前创建指令 - $broadcast timing issue in angularJS, how to ensure directive is created before broadcasting 如何确保在执行第二次迭代之前完成循环的第一次迭代? - How to ensure first iteration of a loop is finished before executing second iteration? 可以使用promises来确保在请求完成之前不使用来自AJAX请求的数据吗? - Can promises be used to ensure data from AJAX request is not used before the request completes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM