Angular get to JSON file displaying as empty

2019-08-03 03:25发布

问题:

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
});