0

我正在尝试通过 AngularJS 工厂和服务方法访问以下 JSON 结构的属性:

{
    "@context": {
        "firstname": "http://xmlns.com/foaf/0.1/firstname",
        "lastname": "http://xmlns.com/foaf/0.1/lastname"
    },
    "members":[
        {
            "firstname":"Debjit",
            "lastname":"Kumar"
        },
        {
            "firstname":"Hari",
            "lastname":"Haran"
        },
        {
            "firstname":"Kaushik",
            "lastname":"Shrestha"
        }
    ]
}

但我无法检索检索到的 JSON 对象的属性。以下是我的 angularJS 代码:

angular.module('rdfa',['ngResource']).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/', {controller: RdfaCtrl});
}])
.factory('members', function($resource){
    return $resource('Json.json', {}, { query: {method:'GET', isArray:false} } );
})
.service('jsonservice',function(members){
    this.members=members.query();
});
function RdfaCtrl($scope,jsonservice){
    $scope.members=jsonservice.members.members;
    console.log(jsonservice.members);  // outputs correct JSON structure
    console.log(jsonservice.members.members);  // outputs undefined
    console.log(jsonservice.members['@context']);  // outputs undefined
}
4

1 回答 1

2

您正在发出异步 HTTP 请求,您不能只是简单地在同一个调用周期打印输出。为此,您需要在query操作中添加成功回调处理程序,例如:

members.query(function(value) {
  console.log(value); // Resource object
  console.log(value.members); // members object      
  console.log(value['@context']);  // @context object
});

检查此 plunker 以获取工作示例:http ://plnkr.co/edit/TFlQ6cDkIA3rpjkvHtOA?p=preview

于 2013-03-04T12:25:02.423 回答