2014-05-07 6 views
5

Come rendere angularjs $ resource restituisce un array di oggetti derivati ​​/ prototipati da un oggetto dominio specificato?

Ecco un esempio su http://plnkr.co/edit/AVLQItPIfoLwsgDzoBdK?p=preview che elabora un set di oggetti Note s.

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

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

Il problema è che i rendimenti $ risorsa gamma di Resource s e non una serie di Note s con Resource metodi aggiunti ai prototipi.

[soluzione deve seguire "buona" javascript pratiche]

+0

un follow-up: http://stackoverflow.com/questions/23528451 dati – okigan

risposta

10

Ecco il plunker completato. Sì, il json grezzo viene analizzato nell'oggetto JSON. Sta usando transformResponse come menzionato da 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; 
    } 
]); 

Giusto per mostrare il titolo non viene utilizzato dalla risorsa grezza, ho modificato title-noteTitle in Note e in html.

+1

per l'analisi JSON, è possibile utilizzare il framework Angular utilizzando var jsonData = angular.fromJson (dati); – Spencer

+0

Sì sicuramente un'opzione, aggiornata di conseguenza, grazie. @Spencer – dmahapatro

+0

Bello! aggiornato plunker: http://plnkr.co/edit/AVLQItPIfoLwsgDzoBdK?p=preview – okigan

1

È possibile manipolare i dati utilizzando transformResponse opzione nella definizione di servizi di risorse (assicuratevi di impostare IsArray 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; 
       } 
      } 
     } 
    ); 
}); 
+0

sembra essere JSON grezzo, non oggetti - si prega di completare la soluzione (in plunker finestra di messaggio il pulsante mostrerà) – okigan

+0

Nei commenti si dice : "trasforma in array di oggetti" è necessario aggiungere la propria logica. –

Problemi correlati