我有一个 Rails 应用程序,并使用 ng-resource 通过 JSON API 访问两个模型。
在我的模板中,我显示第一个模型“订单”的列表:
<li ng-repeat="order in orders">
Order {{order.id}}:
Product: {{showProduct(order.product_id)}}
</li>
每个“订单”都包含一个product_id
。现在我想访问第二个模型(“产品”)并在 ng-repeat
内显示正确的“产品”以及相应“订单”的 ID product_id
.
为了实现这一目标,我考虑使用函数 showProduct()
并使用 order.product_id
作为参数。然而,当我这样做时,它会导致无限循环,不断向我的数据库发出 GET 请求。
这是我的app.js的重要部分
var app = angular.module('shop', ['ngResource']);
app.factory('models', ['$resource', function($resource){
var orders_model = $resource("/orders/:id.json", {id: "@id"}, {update: {method: "PUT"}});
var products_model = $resource("/products/:id.json", {id: "@id"}, {update: {method: "PUT"}});
var o = {
orders: orders_model,
products: products_model
};
return o;
}]);
app.controller('OrdersCtrl', ['$scope', 'models', function($scope, models){
$scope.orders = models.orders.query();
$scope.showProduct = function(product_id){
return models.products.get({id: product_id});
};
}])
这些是我的控制台中的错误(这是有道理的,因为它是一个无限循环):
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
Rails 控制台中的 GET 请求看起来没问题。也许我试图想得比我需要的复杂得多。
最佳答案
是的,因为 View 中有 showProduct
,所以每个摘要都会调用该函数,每次都会返回不同的 Promise,因此它会中断:
- 每个摘要都会多次创建服务器请求
- 每个请求都不同
- 进行 10 次迭代,直到两个值相等或引发异常
我建议你这样做:
models.orders.query().$promise
.then(function(orders){
$scope.orders = orders;
//using lodash here, I recommend you use it too
_.each(orders, function(order){
models.products.get({id: order.product_id }).$promise
.then(function(product){
order.product = product;
})
});
});
在 View 中:
<li ng-repeat="order in orders">
Order {{order.id}}:
Product: {{order.product}}
</li>
<小时/>
但是使用此代码将为每个订单触发一个查询,这是非常糟糕的:它是一种 N+1 反模式。
2个解决方案:
- 让订单直接包含产品数据
- 只有一个请求包含所有产品 ID
关于javascript - 通过 $scope 访问函数中的 ng-resource 会导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33143027/