Javascript / Loopback - array.length返回0

时间:2017-02-19 12:38:00

标签: javascript arrays node.js loopback

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

这是我的代码:

lemma cd : "card {m∈ℕ. m < (4 :: 'a :: linordered_semidom)} = 4"
proof -
  have "{m∈ℕ. m < (4 :: 'a)} = {m∈ℕ. m < (of_nat 4 :: 'a)}" by simp
  also have "… = of_nat ` {m. m < 4}"
    unfolding Nats_def by (auto simp del: of_nat_numeral)
  also have "card … = 4" by (auto simp: inj_on_def card_image)
  finally show ?thesis .
qed

链接:screenshot of the output

3 个答案:

答案 0 :(得分: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 docs:

  

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

答案 1 :(得分:0)

将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){

});

答案 2 :(得分:0)

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,因为此时未能解决承诺。