AngularJS中的$ resource关系 [英] $resource relations in AngularJS

查看:122
本文介绍了AngularJS中的$ resource关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在AngularJS中定义隔离资源的常用方法是:

The usual way of defining an isolated resource in AngularJS is:

angular.service('TheService', function($resource){
  return $resource('api/url');
});

我正在试图找出编写与其他模型相关的模型的最佳方法,例如作为订单,其中包含1个或更多 OrderItem s。我的第一个想法是:

I'm trying to figure out the best way to write a model that relates to other models, such as an Order that has 1 or more OrderItems. My first idea is this:


  1. 创建 OrderService OrderItemService 作为独立资源模型

  2. 编写一个查询 OrderService 的控制器并监视结果数组

  3. 当结果数组发生变化时,查询所有商品ID的 OrderItemService 并装饰订单带有扩展信息的对象

  1. Create the OrderService and OrderItemService as independent resource models
  2. Write a controller that queries the OrderService and watches the result array
  3. When the result array changes, query the OrderItemService for all of the item IDs and decorate the order object with extended information as it comes in

这看起来有点乱。有更优雅的方式吗?

That seems a bit messy. Is there a more elegant way?

推荐答案

angular.service('OrderItem', function($resource) {
  return $resource('api/url/orderItem');
});

angular.service('Order', function($resource, OrderItem) {
  var Order = $resource('api/url/order');

  Order.prototype.items = function(callback) {
    return order.query({orderId: this.id}, callback);
  }
  return Order
});

上述内容会解决您的问题吗?然后你将它用作

Would something like above solve your problem? You would then use it as

var order, items;

Order.get({id: 123}, function(o) {
  order = o;
  o.items(function(is) { items = is; });
});

Angular的$资源不理解关系。这是我们想要在1.0之后更改的内容。

Angular's $resource does not understand relationships. It is something we would like to change in post 1.0.

我认为你不应该直接将数据放在订单上,因为它不是它的一部分,并且你会遇到问题,因为它现在也会有物品对象。

I don't think you should put the data on the order directly, since it is not part of it, and you will have issues persisting the order since it will now have the items object as well.

这篇关于AngularJS中的$ resource关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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