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

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

问题描述

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

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

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

我正在尝试找出编写与其他模型相关的模型的最佳方法,例如具有 1 个或多个 OrderItemOrder.我的第一个想法是:

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. 创建OrderServiceOrderItemService 作为独立的资源模型
  2. 编写一个控制器来查询OrderService并观察结果数组
  3. 当结果数组发生变化时,查询 OrderItemService 以获取所有项目 ID,并在 order 对象出现时使用扩展信息装饰它
  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 的 $resource 不理解关系.这是我们希望在 1.0 后改变的东西.

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

我认为您不应该将数据直接放在订单上,因为它不是订单的一部分,而且您将在坚持订单时遇到问题,因为它现在也将拥有 items 对象.

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天全站免登陆