妥善包装以$资源新的域对象实例 [英] Properly wrap new domain object instance with $resource

查看:118
本文介绍了妥善包装以$资源新的域对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为后续行动,以 $资源返回数组[OO]对象如何正确地包裹从$新的领域对象实例资源

As a follow up to $resource to return array of [OO] objects how to properly wrap new domain object instances from $resource

app.factory('NoteResource', ['$resource', function($resource) {

  var res = $resource('http://okigan.apiary.io/notes/:id', null, ...);

  res.newInstance = function() {
    return angular.extend(new Note(), res);
  };
}

NoteResource.newInstance()应符合标准节省$ / $更新方法返回的对象。

NoteResource.newInstance() shall return object with standard $save/$update methods.

最好修改 plunker 和观看 交通 然后选择新建笔记按钮将正常工作。

Best to modify the plunker and watch traffic then "New note" button shall work correctly.

推荐答案

更新时间:

下面是一种方法,你可以继续将您的注意构造到 $资源服务...

Here is a way you can continue incorporate your Note constructor into your $resource service...

添加一个新的实例方法,从工厂返回的对象:

Add a new instance method to the object returned from the factory:

res.getNew = function(){
  var newNote = new Note();
  newNote.id = undefined; // new note doesn't have id set
  newNote.checked = undefined; // don't need this data passed to server?
  angular.extend(newNote, res);
  return newNote;
}

该方法对象(删除ID并创建一个新的笔记的时候,这并不需要传递到服务器的其他数据)合并之前修改实例化注与 $资源服务和对象返回给调用者。

This method modifies an instantiated Note object (to remove ID and other data that doesn't need to be passed to the server when creating a new note) before merging it with the $resource service and returning that object to the caller.

从您的控制器调用该方法的返回值的局部变量赋值。您也可以从控制器修改其属性:

Call that method from your controller assigning its return value to a local variable. You can also modify its properties from the controller:

var note = NoteResource.getNew();
note.title = 'Eat a lot of junk food';

调用上的注意对象保存方法,将自己作为唯一的参数:

Call the save method on the note object, passing itself as the sole parameter:

note.save(note).$promise.then(function() {
  $scope.notes = NoteResource.query();
  $scope.newNotes = [];
});

手表开发工具,注意,这样做导致JSON有效载荷包含你的注意POST发送属性(您previous解决方案没有)

Watch in dev tools and notice that this does result in a JSON payload being sent with the POST containing your note properties (which your previous solution did not).

希望这个解决方案列举了你的盒子强制执行的模式,而无需在一个意想不到的方式使用的工厂。

Hopefully this solution ticks off your box for enforcing a model without having to using a factory in an unintended manner.

Plunker演示

这篇关于妥善包装以$资源新的域对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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