【发布时间】:2018-01-19 21:29:24
【问题描述】:
所以我的问题可能有点奇怪,但我遇到的问题实际上也很奇怪。
因此,为了创建自定义搜索过滤器,我使用javascript 的.map 和.reduce 函数,在这种情况下,我在我的范围示例中使用这些。看看下面的代码:
$http.get('config/get/getOrders.php', {cache: true}).then(function(response){
$scope.orders = response.data.orders.order;
$scope.orders.map( function addPlace(item) {
item.firstname = $scope.customers.reduce(function(a,customers){
return item.id_customer === customers.id ? customers.firstname : a;
}, '');
return item;
});
});
所以在$http.get() 中,我请求一个带有数据的 JSON 文件。该数据由一些带有信息的订单组成。所有这些订单都有一个id_customer 值。此值连接到下订单的客户信息。
所以我想用customer name 扩大我的搜索功能。有关如何以及为什么查看我昨天问过的question 的更多信息。
它奏效了。过滤器还可以搜索customer_firstname。但后来我想在另一个控制器中使用相同类型的功能。功能目标保持不变。连接来自多个 $scope 类型的数据。但奇怪的是返回是TypeError: Cannot read property 'reduce' of undefined。是的,我把它放在同一个 app.js 中,但只是放在另一个控制器中。我已经检查了 $scope.products 和 $scope.stock_availables 和 $scope.productCombiantions 的所有数据是否存在,并且确实存在,我已经检查了提供商等,并且所有这些都适合我,所以我不知道为什么会这样。本例中的函数为:
$http.get('config/get/getProducts.php', {cache: true}).then(function(response){
$scope.products = response.data.products.product;
$scope.products.map( function addPlace(item) {
item.eanCombination = $scope.productCombinations.reduce(function(a, productCombinations, stock_availables){
return item.id === stock_availables.id + stock_availables.id === stock_availables.id_product_attribute + stock_availables.id_product_attribute === productCombinations.id ? productCombinations.ean13: a;
}, '');
return item;
});
});
简短的总结:一个功能在一个控制器中可以工作,但相同的功能在另一个控制器中不工作。
如果您有任何问题,请在 cmets 中提问。
一如既往,提前致谢!
【问题讨论】:
-
在调用
.reduce之前的某个时间点,$scope.productcombinations会在某个时间点重新创建/重新分配某些异步调用,这可能会导致一些竞争条件。但是,这只是一个猜测,因为我不知道您的其余相关代码在做什么。 -
不,但我已经发现了错误。它确实与调用所有内容的顺序有关。谢谢!
标签: javascript angularjs json