【问题标题】:AngularJS not displaying API dataAngularJS 不显示 API 数据
【发布时间】:2015-08-28 00:42:40
【问题描述】:

我是 AngularJS 的新手。我正在尝试从 API 中检索名字、姓氏和状态,使用状态码的搜索功能,例如“DC”,例如。

我已经修改为更简单了,但我仍然在页面上看不到任何结果:

这是我的收获:

    function ItemsController($scope, $http){
    $http.get("https://my.ncarb.org/Public/api/certification/search?statecode=dc")
    .success(function(data, status, headers, config){
      $scope.items = data;
  });
}

这是我的 api 示例:

{
  "data": [
    {
      "id": "14e1047c-b811-40f7-8a21-780ae5edf1ed",
      "firstName": "Kent",
      "lastName": "Abraham",
      "city": "WASHINGTON",
      "stateCode": "DC",
      "countryCode": "USA"
    },]
}

这是我的 HTML:

  <body ng-controller="ItemsController">
    <h1>jSON Data</h1>
    <table>
      <tr ng-repeat="item in items">
        <td>{{item.id}}</td>
        <td>{{item.firstName}}</td>
        <td>{{item.stateCode}}</td>
      </tr>  
    </table>
  </body>

但是我的输出,经过检查,获得 200 OK 状态,但页面上没有显示任何内容...有什么原因吗?

附加 - 开发工具中的响应屏幕截图

【问题讨论】:

  • 这行$http.get($scope.state.statecode) .then(onStates); 是什么意思?它会做正确的ajax调用吗?
  • 在get()方法中,我试图获取所有的状态码
  • 但状态码实际上是否包含 URL?您是否验证了您在 onstates 中获得的数据是否正确?
  • statecode 不包含 URL。如何验证我在 onState 中获取的数据?

标签: javascript angularjs asp.net-mvc-4


【解决方案1】:

你做错了。 $http.get 返回一个承诺。

这是工作示例。

HTML:

<div ng-app="app">
    <div ng-controller="ItemsController">
        <h1>jSON Data</h1>
        <table>
            <tr ng-repeat="item in items">
                <td>{{item.id}}</td>
                <td>{{item.firstName}}</td>
                <td>{{item.stateCode}}</td>
            </tr>
        </table>
    </div>
</div>

Angular 应用和控制器:

var module = angular.module('app', []);
angular.module('app').controller('ItemsController', ['$scope', '$http', function ($scope, $http) {
    $http.get('https://my.ncarb.org/Public/api/certification/search?statecode=dc').then(function (response) {
         // this callback will be called asynchronously
         // when the response is available
        $scope.items = response.data.data;
    }, function (response) {
          // called asynchronously if an error occurs
          // or server returns response with an error status.
    });
}]);

输出:

【讨论】:

  • 谢谢@Bhushan Firake,我复制了你的javascript/控制器,它就像一个魅力。所以,对于 $http.get(),我应该总是用 .then() 附加它?
  • @Ron 乐于助人。关于.then(),我建议你阅读docs.angularjs.org/api/ng/service/$q
【解决方案2】:

数据是来自 api 的完整响应。

只要做:

$http.get("https://my.ncarb.org/Public/api/certification/search?statecode=dc")
    .success(function(data, status, headers, config){
    $scope.items = data.data;
});

它会解决你的问题:)

【讨论】:

  • 谢谢@Mahaveer Jain,会试一试
  • @Ron 很高兴为您提供帮助。你也可以试试 .then :)
【解决方案3】:

你为什么要做第二个 $http.get() ?如果第一个返回 api 的样本,它是没用的,因为你应该传递一些返回响应的东西在你的 $http.get() 参数中

也许你应该在调用你的 API 之后 make$scope.states = response.data。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    相关资源
    最近更新 更多