2013-03-17 70 views
12

我試圖使用$資源從一個靜態的JSON文件中獲取數據,並在這裏是代碼片段:

angular.module('app.services', ['ngResource']). 
    factory('profilelist',function($resource){ 
    return $resource('services/profiles/profilelist.json',{},{ 
     query:{method:'GET'} 
    }); 
}); 

在控制器中,

function ProfileCtrl($scope,profilelist) { 
$scope.items = []; 
$scope.profileslist = profilelist.query(); 
for (var i=0;i<=$scope.profileslist.length;i++){ 
    if($scope.profileslist[i] && $scope.profileslist[i].profileid){ 
     var temp_profile = $scope.profileslist[i].profileid; 
    } 
    $scope.items.push(temp_profile); 

} 

但現在,我面臨一個錯誤: TypeError: Object #<Resource> has no method 'push'

你能幫我,我哪裏出錯了嗎?

+1

我不知道,但是請注意,.query()不是同步操作,這意味着你可以在結果沒有立即迭代。 – finishingmove 2013-03-17 22:09:37

+0

你說得對。我用回調來遍歷結果。 – codejammer 2013-03-18 13:53:26

回答

21

您不需要爲默認$resource方法(這些是'get','save','query','remove','delete')指定操作參數。在這種情況下,你可以使用.query()方法是(這僅需要服務定義中chaged):

angular.module('app.services', ['ngResource']). 
    factory('profilelist',function($resource){ 
    return $resource('services/profiles/profilelist.json'); 
    }); 

附:而一個更暗示是你的榜樣展開JSON轉換成散列而不是數組(這就是爲什麼你沒有收到推送方法錯誤),如果你需要它是一個數組設置isArray: true行動的配置:

'query': {method:'GET', isArray:true} 

正如@ finishingmove發現你真的不能分配$resource結果立即獲取,提供的回調:

$scope.profileslist = profilelist.query(function (response) { 
    angular.forEach(response, function (item) { 
     if (item.profileid) { 
      $scope.items.push(item.profileid); 
     } 
    }); 
}); 
+0

非常感謝Dmitry Evseev。我也嘗試了下面的代碼,它工作,但你的答案更容易! 'angular.module('upe.services',['ngResource'])。工廠('Profileslst',函數($ resource){ }返回$ resource('services/profiles /:profileid.json',{},{ query:{method:'GET',params:{profileid:'profilelist '},isArray:true} }); });' – codejammer 2013-03-17 22:22:26