Angular JS REST API GET不显示数据

Angular JS REST API GET Not displaying data

本文关键字:显示 数据 GET API JS REST Angular      更新时间:2023-09-26

此处为Nooby问题。我有JSON格式的测试销售数据,并希望使用Angular JS在表中显示数据。

这是角度代码。

var SalesDataApp = angular.module("SalesDataApp", []);
app.factory("services", ['$http', function ($http) {
var serviceBase = '/api/sales';
var obj = {};
obj.getCustomers = function () {
    return $http.get(serviceBase);
};
return obj;
}]);
app.controller('SalesDataController', function ($scope, services) {
services.getCustomers().then(function (data) {
    alert(JSON.stringify(data));
    $scope.customers = data;
});
});

我知道有更好的方法可以做到这一点,但我只是深入研究Angular。。。这是我的HTML。。

<div ng-controller="SalesDataController">
<table class="table table-striped" >
 <tr><th>ID</th>
 </tr>
     <tr ng-repeat="a in salesData">
         <td>{{a.Index}}</td>
     </tr>
 </table>
 </div>

我做了一个测试,看看angular是否有效,这是一个赢家,但代码没有显示任何内容。我到底哪里错了?

感谢

我在您的控制器中没有看到任何名为salesData的变量,可能您需要在html中将其称为customers。

<div ng-controller="SalesDataController">
<table class="table table-striped" >
 <tr><th>ID</th>
 </tr>
     <tr ng-repeat="a in customers">
         <td>{{a.Index}}</td>
     </tr>
 </table>
 </div>

同时更改您的应用程序名称

发件人:

var SalesDataApp = angular.module("SalesDataApp", []);

收件人:

var app = angular.module("SalesDataApp", []);
var app = angular.module("SalesDataApp", []);
app.factory("services", ['$http', function ($http) {
  var serviceBase = '/api/sales';
  var obj = {};
  obj.getCustomers = function () {
    return $http.get(serviceBase);
  };
  return obj;
}]);
app.controller('SalesDataController', function ($scope, services) {
  services.getCustomers().then(function (data) {
    console.log(data); //changed
    $scope.customers = data;
  });
});

我在serviceBase字符串中添加了.json。我假设sales.json文件位于相对于此应用程序的正确位置您现在应该可以在控制台中看到数据。根据它在JSON文件中的格式,它现在可能也在UI中。如果不是,则需要使用控制台中显示的数据结构正确设置$scope.customers。