0

I am trying to access properties of the following JSON structure through AngularJS factory and service methods:

{
    "@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"
        }
    ]
}

But I am not able retrieve properties of the retrieved JSON object. The following is my angularJS code:

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 Answer 1

2

You are making an asynchronous HTTP request, you cannot just simply print the output on the same call cycle. In order to do that you need to add a success callback handler in the query action, for example:

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

Check this plunker for a working example: http://plnkr.co/edit/TFlQ6cDkIA3rpjkvHtOA?p=preview

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.