Pregunta

How to make angularjs $resource return an array of objects derived/prototyped from specified domain object?

Here is an example on http://plnkr.co/edit/AVLQItPIfoLwsgDzoBdK?p=preview that processes a set of Notes objects.

app.controller('MainCtrl', function($scope, NoteResource) {
$scope.name = 'World';
$scope.notes  = NoteResource.query();

$scope.spellCheckAllNotes = function() {
  angular.forEach($scope.notes, function(note) {
    note.spellCheck();
   });
 }
});

The issue is that $resource returns array of Resources and not an array of Notes with Resource methods added to prototypes.

[solution shall follow "good" javascript practices]

¿Fue útil?

Solución

Here is the completed plunker. Yes raw json is parsed to JSON object. It is using transformResponse as mentioned by Armando.

app.factory('NoteResource', ['$resource',
  function($resource) {
    var res =  $resource('http://okigan.apiary.io/notes/:id', {}, {
      query: {
        method: 'GET',
        params: {
        },
        isArray: true,
        transformResponse: function(data, header){
          //Getting string data in response
          var jsonData = JSON.parse(data); //or angular.fromJson(data)
          var notes = [];

          angular.forEach(jsonData, function(item){
            var note = new Note();
            note.noteTitle = item.title;  
            notes.push(note);
          });

          return notes;
        }
      }
    });
    return res;
  }
]);

Just to show title is not used from the raw resource, I modified title to noteTitle in Note and in html.

Otros consejos

You can manipulate your data using transformResponse option in your resource service definition (make sure to set isArray to true):

angular.module('services', ['ngResource']).
    factory("yourService", function ($resource) {
        return $resource(
            '/custom/url', {}, {
            get: {
                method: 'GET',
                isArray: true,
                transformResponse: function(data, headers){
                    //
                    // transform to array of objects 
                    return data;
                }
            }
        }
    );
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top