使 angularjs $resource 返回 [OO] 对象数组 [英] Make angularjs $resource return array of [OO] objects

查看:25
本文介绍了使 angularjs $resource 返回 [OO] 对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让 angularjs $resource 返回从指定域对象派生/原型化的对象数组?

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

这是一个关于 http://plnkr.co/edit/AVLQItPIfoLwsgDzoBdK?p=preview 的示例 处理一组 Note 的对象.

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();
   });
 }
});

问题在于 $resource 返回 Resource 的数组,而不是 Note 的数组,其中 Resource 方法添加到原型中.

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

[解决方案应遵循良好"的 javascript 实践]

[solution shall follow "good" javascript practices]

推荐答案

这是完整的 plunker.是的,原始 json 被解析为 JSON 对象.它正在使用 Armando 提到的 transformResponse.

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;
  }
]);

只是为了显示原始资源中未使用的标题,我在 Note 和 html 中将 title 修改为 noteTitle.

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

这篇关于使 angularjs $resource 返回 [OO] 对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆