最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - $resource relations in AngularJS - Stack Overflow

programmeradmin6浏览0评论

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

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

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. 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?

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

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

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. 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?

Share Improve this question edited Aug 18, 2017 at 6:10 Graham 7,80220 gold badges64 silver badges91 bronze badges asked Apr 2, 2012 at 17:41 Ben StraubBen Straub 5,7763 gold badges29 silver badges43 bronze badges 3
  • it raises "TypeError: angular.service is not a function" – zVictor Commented Jun 14, 2012 at 17:51
  • IIRC, I asked this when Angular was pre-1.0. The API has likely changed since then. – Ben Straub Commented Jun 14, 2012 at 18:16
  • No problem, I created an updated question: stackoverflow.com/q/11038425/599991 – zVictor Commented Jun 14, 2012 at 22:42
Add a comment  | 

1 Answer 1

Reset to default 18
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'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.

发布评论

评论列表(0)

  1. 暂无评论