使用AngularJS $资源获取数据

cod*_*mer 12 javascript angularjs

我试图使用$ resource从静态json文件中获取数据,这里是代码片段:

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

在控制器中,

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);

}
Run Code Online (Sandbox Code Playgroud)

但现在,我面临一个错误: TypeError: Object #<Resource> has no method 'push'

你能在我出错的地方帮助我吗?

Dmi*_*eev 21

您不需要为默认$resource方法指定actions参数(这些是'get','save','query','remove','delete').在这种情况下,您可以.query()按原样使用方法(这只需要对服务定义进行查询):

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

PS还有一个提示是你的示例将json打包成哈希而不是数组(这就是为什么你没有收到push方法错误),如果你需要将它作为一个数组设置isArray: true为动作配置:

'query':  {method:'GET', isArray:true}
Run Code Online (Sandbox Code Playgroud)

并且正如@finishingmove发现你真的无法分配$ resource结果立即获得,提供回调:

$scope.profileslist = profilelist.query(function (response) {
    angular.forEach(response, function (item) {
        if (item.profileid) {
            $scope.items.push(item.profileid);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)