AngularJS 中的 $resource 关系 [英] $resource relations in AngularJS
问题描述
在 AngularJS 中定义隔离资源的常用方法是:
The usual way of defining an isolated resource in AngularJS is:
angular.service('TheService', function($resource){
return $resource('api/url');
});
我正在尝试找出编写与其他模型相关的模型的最佳方法,例如具有 1 个或多个 OrderItem
的 Order
.我的第一个想法是:
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:
- 创建
OrderService
和OrderItemService
作为独立的资源模型 - 编写一个控制器来查询
OrderService
并观察结果数组 - 当结果数组发生变化时,查询
OrderItemService
以获取所有项目 ID,并在order
对象出现时使用扩展信息装饰它
- 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
好像有点乱.有没有更优雅的方式?
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屋!