小编典典

使用AngularJS $ resource获取数据

angularjs

我正在尝试使用$ resource从静态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'

你能帮我解决我的问题吗?


阅读 272

收藏
2020-07-04

共1个答案

小编典典

您不需要为默认$resource方法指定动作参数(这些方法是“ get”,“ save”,“ query”,“ remove”,“
delete”)。在这种情况下,您可以.query()按原样使用method(这仅需要更改服务定义):

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

PS还有一个提示是,如果您需要将其作为设置isArray: true为action config
的数组,则示例将json展开为哈希而不是数组(这就是为什么未收到push方法错误的原因)的原因:

'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);
        }
    });
});
2020-07-04