简体   繁体   中英

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. I'm building a fronend with AngularJS. Later the date will be retrieved from an API, but now I'm simply read it from a local JSON file. 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 .

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? And since it's currently taking place in the AngularJS context: (2) Is there a specific Angular solution for this problem?

EDIT

How to solve this problem in AngularJS?

Yes, as proposed in the comments $http is the easiest way to do ajax requests in Angular.

You could also use ngResource if you're having a RESTful backend that you're interacting with.

Please have a look at the demo below and here at jsfiddle .

It shows the usage of $http service.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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