如何通过angularjs $ resource访问json中的嵌套对象

时间:2013-02-20 06:29:17

标签: json rest angularjs nested

我有提供REST服务的.NET WCF服务。一切都适合我,直到我尝试发送嵌套对象的对象。然后我在angularjs中得不到任何东西。如何使用/访问嵌套对象进行数据交换?

.NET服务部分:

[OperationContract] // route prefix 'api'
    [WebGet(UriTemplate = "users/{id}/privileges", ResponseFormat = WebMessageFormat.Json)]
    public PrivilegeSet GetPrivileges(string id)
    {
        var response = new PrivilegeSet();

        List<Role> roles = new List<Role>();
        roles.Add(new Role() { RoleId = 1, Name = "Role 1", Active = true });
        roles.Add(new Role() { RoleId = 2, Name = "Role 2", Active = true });
        roles.Add(new Role() { RoleId = 3, Name = "Role 3", Active = false });
        response.Roles = roles;

        List<SubRole> subRoles = new List<SubRole>();
        subRoles.Add(new SubRole() { SubRoleId = 1, Name = "SubRole 1", RoleId = 1, Active = true });
        subRoles.Add(new SubRole() { SubRoleId = 2, Name = "SubRole 2", RoleId = 1, Active = true });
        subRoles.Add(new SubRole() { SubRoleId = 3, Name = "SubRole 3", RoleId = 1, Active = false });
        response.SubRoles = subRoles;

        return response;
    }

JSON结构:

{
"Roles": [
{
  "Active": true,
  "Name": "Role 1",
  "RoleId": 1
},
{
  "Active": true,
  "Name": "Role 2",
  "RoleId": 2
},
{
  "Active": false,
  "Name": "Role 3",
  "RoleId": 3
}
],
"SubRoles": [
{
  "Active": true,
  "Name": "SubRole 1",
  "RoleId": 1,
  "SubRoleId": 1
},
{
  "Active": true,
  "Name": "SubRole 2",
  "RoleId": 1,
  "SubRoleId": 2
},
{
  "Active": false,
  "Name": "SubRole 3",
  "RoleId": 1,
  "SubRoleId": 3
}
]
}

Angularjs服务:

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

Angularjs获取部分:

function PrivilegesCtrl($scope, Privilege) {
    $scope.privileges = Privilege.query({userId:2}); // privileges remains empty using nested objects, with one level object works fine
    ...

当JSON具有嵌套对象时,为什么权限保持为空?以及如何在视图中访问嵌套对象?

1 个答案:

答案 0 :(得分:8)

当您使用$resource服务时,.query操作会假定您的响应是一个数组。使用.query时,通过在使用以下第三个参数创建资源时指定响应,可以指定响应不是数组:

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

查看this plnkr以获取示例。如果您取出{'query': {method:'GET', isArray:false}},您的回复将是一个空数组。

注1:您的控制台可能显示错误TypeError: Object #<Resource> has no method 'push',在使用.query时,通常意味着您的REST调用需要一个数组。

注2:资源操作默认值在$resource文档中描述如下:

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