【问题标题】:$http JSON request not working in angularjs$http JSON请求在angularjs中不起作用
【发布时间】:2016-02-03 15:39:48
【问题描述】:

我正在使用 angularJS 从文件中获取 JSON 数据。这样做不会让我得到文件中的数据。我的plunker link

HTML

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

控制器

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

});

【问题讨论】:

    标签: javascript angularjs json http


    【解决方案1】:

    您必须将结果的分组移动到 .then 方法中,否则它将在您获得 get 请求的结果之前被调用:

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

    【讨论】:

    • 您的答案是我正在寻找的,但不是 list.json,而是提供 API url 也不会反映任何答案,API url plunk
    • @RohitKumarVinay 这是因为外部 url 并不总是包含数组中带有 orderfood 项目的项目。当它不包含 orderfood 数组中的项目时,它将在 each.orderfood[0].name 上抛出错误,因为 each.orderfood[0] 未定义。当您在分组功能中遇到错误时,您将不会收到任何输出。这种错误在您的浏览器控制台中是可见的,利用它对您有利。我添加了一个 if 语句来防止这些错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多