2013-03-01 114 views
0

我試圖通過AngularJS工廠和服務方法來訪問以下JSON結構的屬性來訪問JSON代碼屬性:無法通過angularJS服務

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

回答

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