使用Angularjs与Django Restful API交互

时间:2015-09-08 15:57:37

标签: angularjs django-rest-framework angular-resource

我正在尝试使用$ resource与我的Django Restful API进行交互,但是当我尝试获取或查询时,它会返回> 7000个元素。它就像是单独返回api的每个字母/组件一样。我也尝试过使用' /api/projects.json /' (遵循Angularjs教程)和' / api / projects /?format = json'查询api,但我得到了相同的结果。我错过了什么?

我的服务:

(function(){
angular
    .module('userdash.projects.services')
    .factory('ProjectServ', ProjectServ);

ProjectServ.$inject = ['$resource'];

function ProjectServ($resource){
    return $resource('api/projects/', {},{
        create: {method: 'POST'},
        get: {method: 'GET', isArray:false},
        remove: {method: 'DELETE'},
        update: {method: 'PUT'}
    })
}
})();

我的控制器:

(function(){

angular
    .module('userdash.projects.controllers')
    .controller('ProjectController', ProjectController);

ProjectController.$inject = ['$scope','ProjectServ'];

function ProjectController($scope, ProjectServ){
     ProjectServ.get().$promise.then(function(data){
        $scope.projects = ProjectServ.get();
     });
}

我的指令HTML:

<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main" ng-controller="ProjectController">
<div class="row">
  <div class="col-md-4" ng-repeat="project in projects">
      <h2>Heading</h2>
      <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
      <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
    </div>
</div>

Using bootstraps Dashboard template, I get ~>7000 elements in the promise

My RESTfull API

1 个答案:

答案 0 :(得分:0)

首先,如果使用默认方法,则无需指定每个方法。使用$resource('api/projects/')代替:

function ProjectServ($resource){
    return $resource('api/projects/', {},{
        create: {method: 'POST'},
        get: {method: 'GET', isArray:false},
        remove: {method: 'DELETE'},
        update: {method: 'PUT'}
    })
}

在第二位,为了解决您的问题,您应该将承诺中的数据变量分配给本地数组,如下所示:

function ProjectController($scope, ProjectServ){
     ProjectServ.get().$promise.then(function(data){
        $scope.projects = data;
     });
}

干杯!