Angular get to JSON file displaying as empty

2019-08-03 03:05发布

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" }
  ]
}

3条回答
Viruses.
2楼-- · 2019-08-03 03:38

$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
});
查看更多
够拽才男人
3楼-- · 2019-08-03 03:41

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.

查看更多
别忘想泡老子
4楼-- · 2019-08-03 03:47

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.

查看更多
登录 后发表回答