Make angularjs $resource return array of [OO] objects

前端 未结 2 528
不思量自难忘°
不思量自难忘° 2020-12-19 12:07

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/AVLQItPIfoLwsg

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 13:00

    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.

提交回复
热议问题