3

My api basically returns something like this:

GET /api/projects/
{
"count": 26, 
"next": "http://127.0.0.1:8000/api/projects/?page=2", 
"previous": null, 
"results": [
    {
        "id": 21, 
        "name": "Project A",
        ...
    },
    {
        "id": 19, 
        "name": "Project B",
        ...
    },
    ...
]
}

Using NgResource, I am able to query the api and get the data like this:

var PROJECT = $resource('/api/projects/:id/', {id:'@id'},{
    query : {
        method : 'GET',
        isArray : false
    }
});

factory.project_list = function(callback) {
    PROJECT.query({},function(project_list){
        factory.project_list = project_list.results;
        callback();
    });
};

My different projects are now available in factory.project_list. The issue here is that each item in factory.project_list are not ngResource items. So I can't call methods such as .$save(), .$update()...

I saw a transformResponse() function but I'm not able to get it working easily...

Do you have any idea what could be the best approach here ?

Alex Grs
  • 3,231
  • 5
  • 39
  • 58

1 Answers1

3

This is what worked for me:

app.config(['$resourceProvider', function($resourceProvider) {
  $resourceProvider.defaults.stripTrailingSlashes = false;
}]);

services.factory('Project', ['$resource',
    function($resource) {
        return $resource('api/project/:id/', {}, {
            query: {
                method: 'GET',
                url: 'api/projects/',
                isArray: true,
                transformResponse: function(data, headers) {
                    return angular.fromJson(data).results;
                },
            },  
        });
    }
]);
Derrick Petzold
  • 1,118
  • 13
  • 13