12

$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'

どこが間違っているのか教えてください。

4

1 に答える 1

21

$resourceデフォルトのメソッド ('get'、'save'、'query'、'remove'、'delete') のアクション パラメータを指定する必要はありません。この場合、.query()メソッドをそのまま使用できます (これにはサービス定義のみを変更する必要があります)。

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

isArray: truePSそしてもう1つのヒントは、アクション構成に設定された配列にする必要がある場合、あなたの例ではjsonを配列ではなくハッシュにアンラップしたことです(これがプッシュメソッドエラーを受信しなかった理由です) :

'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);
        }
    });
});
于 2013-03-17T22:15:14.027 に答える