【问题标题】:Javascript/Loopback - array.length returns 0Javascript/Loopback - array.length 返回 0
【发布时间】:2017-07-08 17:05:21
【问题描述】:

我正在使用环回读取客户列表/数组。我将客户数组存储在 $scope.customers.customerList 中。当我第一次登录时,数组看起来很好,但是当我得到它的长度时,它似乎丢失了,因为它返回 0。为什么会发生这种情况?

这是我的代码:

    $scope.customers = { customerList: [] };

    var filter = {
           include: {
              relation: 'orders'
           }
    };

    $scope.customers.customerList = Customers.find({filter: filter});
    console.log($scope.customers.customerList);          //outputs array with length 21
    console.log($scope.customers.customerList.length);   //array length is 0

链接:screenshot of the output

【问题讨论】:

标签: javascript arrays node.js loopback


【解决方案1】:

这正是Jonathan Lonowski 所描述的。由ngResource 创建的Customers.find 最初返回一个空数组,并在加载数据时对其进行更新。 By the time the Browser console prints it or when you open it, the results are already there.

来自 Angular 文档:

重要的是要意识到调用 $resource 对象方法 立即返回一个空引用(对象或数组取决于 是数组)。一旦数据从服务器返回,现有的 参考是用实际数据填充的。

【讨论】:

    【解决方案2】:

    使用带有回调函数的 find 方法。

          $scope.customers = { customerList: [] };
    
    var filter = {
           include: {
              relation: 'orders'
           }
    };
    
    Customers.find({filter: filter},function(customerList){
    $scope.customers.customerList=customerList;
    
       console.log($scope.customers.customerList);          //outputs array with length 21
    console.log($scope.customers.customerList.length); 
    },function(error){
    
    });
    

    【讨论】:

      【解决方案3】:

      loopback 中的 find 方法接受一个回调并返回一个 Promise。你可以使用任何一个。

      //callback
      Customers.find({filter: filter}, function (err, customerList) {
        $scope.customers.customerList = customerList;
      });
      
      //Promise
      Customers.find({filter: filter}).then(function(customerList) {
        //customerList is an array
        $scope.customers.customerList = customerList;
      });
      

      您可以在输出中看到承诺已解决并提供了 21 个元素。长度为 0,因为此时承诺尚未解决。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-20
        相关资源
        最近更新 更多