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
$resource relations in AngularJS
提问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 Order
that has 1 or more OrderItem
s. My first idea is this:
我试图找出编写与其他模型相关的模型的最佳方法,例如Order
具有 1 个或多个OrderItem
s 的模型。我的第一个想法是:
- Create the
OrderService
andOrderItemService
as independent resource models - Write a controller that queries the
OrderService
and watches the result array - When the result array changes, query the
OrderItemService
for all of the item IDs and decorate theorder
object with extended information as it comes in
- 创建
OrderService
和OrderItemService
作为独立的资源模型 - 编写一个控制器来查询
OrderService
和观察结果数组 - 当结果数组发生变化时,查询
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 对象。