无法通过angularJS服务访问JSON代码的属性

时间:2013-03-01 06:31:54

标签: json angularjs

我试图通过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
}

1 个答案:

答案 0 :(得分: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