Make angularjs $resource return array of [OO] objects

怎甘沉沦 提交于 2019-11-29 11:03:25

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.

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;
                }
            }
        }
    );
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!