使用AngularJS $资源获取数据
我试图使用$资源从一个静态的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'
你能帮我,我哪里出错了吗?
您不需要为默认$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);
}
});
});
非常感谢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
我不知道,但是请注意,.query()不是同步操作,这意味着你可以在结果没有立即迭代。 – finishingmove 2013-03-17 22:09:37
你说得对。我用回调来遍历结果。 – codejammer 2013-03-18 13:53:26