使用AngularJS $资源获取数据 [英] Using AngularJS $resource to get data

查看:98
本文介绍了使用AngularJS $资源获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用$资源从静态JSON文件中获取数据,并在这里是code片断:

I am trying to use $resource to get data from a static json file and here is the code snippet :

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

}

但现在,我面临的一个错误:
类型错误:对象#&LT;资源与GT;没有方法推

你能帮我在哪里,我错了?

Could you please help me where I am going wrong ?

推荐答案

您不需要指定动作参数默认 $资源方法(这些是'得到' ,保存,查询,删除,删除)。在这种情况下,你可以使用 .query()的方法是(这需要chaged仅服务定义):

You don't need to specify actions parameter for default $resource methods (these are 'get', 'save', 'query', 'remove', 'delete'). In this case you can use .query() method as is (this requires only service definition to be chaged):

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

P.S。还有一的暗示是,你的榜样展开的JSON转换成散列而不是阵列(这就是为什么你没有收到推送方法错误),如果你需要它是一个数组设置 IsArray的:真正的行动配置:

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

和作为@finishingmove看上你真的不能分配 $资源结果立即获得,提供回调

And as @finishingmove spotted you really can't assign $resource result to obtain immediately, provide callback:

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

这篇关于使用AngularJS $资源获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆