javascript AngularJS 中的 $resource 关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9981090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:24:44  来源:igfitidea点击:

$resource relations in AngularJS

javascriptangularjs

提问by Ben Straub

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

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

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 Orderthat has 1 or more OrderItems. My first idea is this:

我试图找出编写与其他模型相关的模型的最佳方法,例如Order具有 1 个或多个OrderItems 的模型。我的第一个想法是:

  1. Create the OrderServiceand OrderItemServiceas independent resource models
  2. Write a controller that queries the OrderServiceand watches the result array
  3. When the result array changes, query the OrderItemServicefor all of the item IDs and decorate the orderobject with extended information as it comes in
  1. 创建OrderServiceOrderItemService作为独立的资源模型
  2. 编写一个控制器来查询OrderService和观察结果数组
  3. 当结果数组发生变化时,查询OrderItemService所有的项目 ID 并在order它进来时用扩展信息装饰对象

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

好像有点乱。有没有更优雅的方式?

回答by Misko Hevery

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.

Angular 的 $resource 不理解关系。这是我们想要在 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.

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