Angular get to JSON file displaying as empty

孤街浪徒 提交于 2019-12-24 12:44:07

问题


I am new to angular and trying to integrate it within my application. I am attempting to use a simple $http.get to a .JSON file, which seems to be found, but when trying to pass the data to the front end, or even alert it, is it alerting as []

Here my get:

$scope.countries = [];
    $http.get('/resources/data/countries-report.json', function(data){
            $scope.countries = data;
        }, function(error) {
            //handle error here
    });

    alert(JSON.stringify($scope.countries));

Here's my .JSON file:

{
  "firstName"   : "Joe",
  "surName" : "Bloggs",
  "countries" : [
      { "name": "France", "population": "63.1" },
      { "name": "Span", "population": "52.3" },
      { "name": "United Kingdom", "population": "61.8" }
  ]
}

回答1:


Try this:

$scope.countries = [];
$http.get('/resources/data/countries-report.json', function(data){
        $scope.countries = data;
alert(JSON.stringify($scope.countries));
    }, function(error) {
        //handle error here
});

Alert should go in the callback.




回答2:


This should do it

$http.get('/resources/data/countries-report.json').success(function(data) {
    $scope.countries = data;
    alert(JSON.stringify($scope.countries));
  }).error(function(error) {
    alert('error');
  });

also this equivalent would work

$http.get('/resources/data/countries-report.json').then(function(data) {
    $scope.countries = data;
    alert(JSON.stringify($scope.countries));
  }, function(error) {
    alert('error');
  });

Edit --

  1. Instead of $http.get('/someUrl', sucessCallback, errorCallback) it should be either

    $http.get('/someUrl').success(successCallback).error(errorCallback) 
    

    or

    $http.get('/someUrl').then(successCallback, errorCallback) 
    

    see docs

  2. Because $http.get is asynchronous alert should be moved in the successCallback function, to ensure that $scope.countries=data is executed before calling alert.




回答3:


$http.get is an async function. when you try alert(JSON.stringify($scope.countries)); $scope.countries is equals to []. You must wait for server response before using data.

Try to do your alert into success function

$scope.countries = [];
$http.get('/resources/data/countries-report.json', function(data){
        $scope.countries = data;
        alert(JSON.stringify($scope.countries));
    }, function(error) {
        //handle error here
});


来源:https://stackoverflow.com/questions/23135773/angular-get-to-json-file-displaying-as-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!