本文介绍了不使用数组Angularjs $资源从REST API返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我努力学习angularjs,并试图数据绑定到一个数组从REST API返回击中块。我有一个简单的API湛蓝人返回对象的数组。服务URL是。

I am trying to learn angularjs, and have hit a block in trying to databind to an array returned from a Rest API. I have a simple azure api returning an array of person objects. Service url is http://testv1.cloudapp.net/test.svc/persons.

我的控制器code如下:

My controller code looks like:

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如下:

My html looks like:

<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不工作?

Question: The table in above html is not displaying any data. I can see the call to the api in Firebug, and can also see the JSON response from the api. What am I doing incorrectly that is causing the databinding to the REST api not work?

PS:演示的jsfiddle这个问题是: http://jsfiddle.net/jbliss1234/FBLFK/4/

PS:JSFiddle demonstrating this issue is at: http://jsfiddle.net/jbliss1234/FBLFK/4/

推荐答案

为了处理与资源$阵列的服务,它的建议您使用查询方法。正如你可以看到下面的查询方法是建立在处理数组。

In order to handle arrays with the $resource service, it's suggested that you use the query method. As you can see below, the query method is built to handle arrays.

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

您应该以这个数组返回到你的范围内使用的code是

The code you should use in order to return this array to your scope is

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工作,并会返回一个数组。

This assumes that your REST API is working and will return an array.

有关进一步阅读头的文档

For further reading head to the docs

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

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

这篇关于不使用数组Angularjs $资源从REST API返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 21:14