2017-02-19 101 views
-2

我正在使用loopback讀取客戶列表/數組。我將客戶數組存儲在$ scope.customers.customerList中。當我第一次登錄時,數組似乎很好,但是當我獲得它的長度時,它似乎會丟失,因爲它返回0.爲什麼會發生這種情況?Javascript/Loopback - array.length返回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

+0

似乎是0是一個有效的值,並且當然可以給出你的代碼,例如,如果過濾器是零結果。 –

+2

在調用console.log()之後,可能會修改數組。開發工具的控制檯正在向您顯示當您查看它時的值 - 「[* console.log()顯示值在實際更改之前的變化值*](https://stackoverflow.com/questions/ 11284663 /控制檯登錄顯示最改變值-A-可變的 - 先接後的值,實際上-CH)「。 「長度」不一樣,因爲從中讀取的數字是不可變的。你可以嘗試'console.dir()'。 –

+0

[console.log()可能的重複顯示值實際更改前變化的值](http://stackoverflow.com/questions/11284663/console-log-shows-the-changed-value-of-一個可變先接後的值,實際上-CH) –

回答

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

}); 
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,因爲承諾在那時尚未解決。