【问题标题】:TypeError: Cannot read property 'reduce' of undefined in angularjsTypeError:无法读取 angularjs 中未定义的属性“减少”
【发布时间】: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


【解决方案1】:

所以我在加载所有数据的顺序中犯了一个错误。因为$scope.productCombinations 是在产品序列之后加载的。所以给大家小费。始终检查编写代码的顺序。

【讨论】:

  • 另外,在数据可能依赖的时候处理多个 Promise 时要小心,因为要知道它们可能会以不可预知的顺序解决。您必须正确使用链接,以确保您在知道其承诺已被解决的地方访问数据。
猜你喜欢
  • 2019-10-02
  • 2015-08-26
  • 2016-09-12
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多