Rohit Vinay
Rohit Vinay

Reputation: 663

$http JSON request not working in angularjs

I am using angularJS to get JSON data from a file. doing so it does not get me the data in the file. My plunker link

HTML

<body ng-controller="MainCtrl">
    <div ng-repeat="(key, data) in groupedByFoodName">
      <p>{{key}} {{data.length}}</p>
    </div>
</body>

Controller

app.controller('MainCtrl', function($scope,$http) {

 $http({
  method: 'GET',
  url: 'list.json'
  }).then(function successCallback(response) {
    $scope.lists = response.data;
  });
 $scope.groupedByFoodName=  _.groupBy($scope.lists, function (each) { return each.orderfood[0].name });

});

Upvotes: 0

Views: 143

Answers (1)

Ricconnect
Ricconnect

Reputation: 1079

You have to move the grouping of your result into the .then method, otherwise it will be called before you have the result of the get request:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,$http) {

$http({
        method: 'GET',
        url: 'https://safe-depths-4702.herokuapp.com/api/orders'
    }).then(function successCallback(response) {
        $scope.orders = response.data;
        $scope.groupedByFoodName=  _.groupBy($scope.orders, function (each) { 
          if(each.orderfood.length > 0) 
            return each.orderfood[0].name; 
        });
    });
});

Upvotes: 4

Related Questions