【问题标题】:Angularjs $resource not working with an array returned from a REST APIAngularjs $resource 不适用于从 REST API 返回的数组
【发布时间】:2016-03-09 04:42:04
【问题描述】:

我正在尝试学习 angularjs,但在尝试将数据绑定到从 Rest API 返回的数组时遇到了障碍。我有一个简单的 azure api 返回一组人员对象。服务网址是http://testv1.cloudapp.net/test.svc/persons

我的控制器代码如下:

angular.module("ToDoApp", ["ngResource"]);
function TodoCtrl($scope, $resource) {
$scope.svc = $resource('http://testv1.cloudapp.net/test.svc/persons', {
    callback: 'JSON_CALLBACK'
}, {
    get: {
        method: 'JSONP',
        isArray: true
    }
});
$scope.items = $scope.svc.get();
$scope.msg = "Hello World";
}

我的 html 看起来像:

<html>
<head></head>
<body>
<div ng-app="ToDoApp">
    <div ng-controller="TodoCtrl">
         <h1>{{msg}}</h1>

        <table class="table table-striped table-condensed table-hover">
            <thead>
                <th>Email</th>
                <th>First Name</th>
                <th>Last Name</th>
            </thead>
            <tbody>
                <tr ng-repeat="item in items">
                    <td>{{item.Email}}</td>
                    <td>{{item.FirstName}}</td>
                    <td>{{item.LastName}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>

问题:上面html中的表格没有显示任何数据。我可以在 Firebug 中看到对 api 的调用,也可以看到来自 api 的 JSON 响应。我做错了什么导致与 REST api 的数据绑定不起作用?

PS:JSFiddle 演示此问题位于:http://jsfiddle.net/jbliss1234/FBLFK/4/

【问题讨论】:

    标签: angularjs angularjs-ng-repeat


    【解决方案1】:

    为了使用 $resource 服务处理数组,建议您使用查询方法。如下所示,查询方法是为处理数组而构建的。

    { 'get':    {method:'GET'},
      'save':   {method:'POST'},
      'query':  {method:'GET', isArray:true},
      'remove': {method:'DELETE'},
      'delete': {method:'DELETE'} };
    

    为了将此数组返回到您的作用域,您应该使用的代码是

    angular.module("ToDoApp", ["ngResource"]);
    
    function TodoCtrl($scope, $resource) {
        var svc = $resource('http://testv1.cloudapp.net/test.svc/persons');
        $scope.items = svc.query();
        $scope.msg = "Hello World";
    }
    

    这假定您的 REST API 正在运行,并将返回一个数组。

    如需进一步阅读,请前往文档

    http://docs.angularjs.org/api/ngResource.$resource

    【讨论】:

      【解决方案2】:

      只是想交叉发布我对 Aleksander 在另一个 stackoverflow 问题上给出的解决方案的改编:https://stackoverflow.com/a/16387288/626810

      methodName: {method:'GET', url: "/some/location/returning/array", transformResponse: function (data) {return {list: angular.fromJson(data)} }}
      

      所以当我调用这个函数时:

      var tempData = ResourceName.methodName(function(){
        console.log(tempData.list); // list will be the array in the expected format
      });
      

      如果您需要在多个方法/资源中获取数组,显然这有点笨重,但它似乎可以工作。

      【讨论】:

      • transformResponse: function (data, headers) { return { count: angular.fromJson(data) } } // 非常适合我。谢谢!
      【解决方案3】:

      如果您有嵌套对象,请使用 isArray 参数:

      angular.module('privilegeService', ['ngResource']).
      factory('Privilege', function ($resource) {
          return $resource('api/users/:userId/privileges', 
                           {userId: '@id'}, 
                           {'query':  {method:'GET', isArray:false}});
      });
      

      您可以使用container.object.property 表示法来访问对象及其属性。

      【讨论】:

      • isArray 参数已经存在。在这种情况下,将其设置为 true 或 false 无效。您能否看一下 jsfiddle 并建议您究竟需要做什么才能绑定数据。谢谢
      【解决方案4】:

      不确定我们是否在使用 json 和 REST 时遇到同样的问题,但这篇文章解决了我的问题:array of strings not rendered correctly through angular resource

      【讨论】:

        【解决方案5】:

        您从服务器返回的数组不是一个干净的数组,但有一些额外的属性。这使得 ng-repeat 在您使用 in 对其进行迭代时不会显示任何内容。

        您需要一个特殊的迭代器从服务器遍历数组,这将忽略那些额外的属性。所以先通过forEach提取数组数据,像这样:

        $scope.items = []
        var response = $scope.svc.get();
        angular.forEach(response, function(item) {
          $scope.items.push(item);
        });
        

        那你就可以了

        <tr ng-repeat="item in items">
        

        【讨论】:

          【解决方案6】:

          我遇到了类似的问题,但没有一个答案对我很有效,这就是我所做的:

              $resource("/", {}, {
                 query: {
                      method: 'GET',
                      isArray: false,
                      transformResponse: function (data, headers) {
                          //if no data return so no warnings
                          if (data == ''){
                              return;
                          }
          
                          return {data: $.extend({}, eval("{" + data + '}'))};
                      }
                  }
             });
          

          使用 jquery。基本上将数组转换为对象,因此 angularjs 资源不会大便。

          【讨论】:

          • 抱歉 eval 解析 JSON ?请不要!使用 JSON.parse!
          猜你喜欢
          • 2014-05-12
          • 1970-01-01
          • 2014-12-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-26
          • 2014-02-25
          • 1970-01-01
          相关资源
          最近更新 更多