2016-08-22 24 views
0

我想過濾一個Firebase路徑,看看我的路徑中是否存在小孩。
我只想返回值有至少一個路徑調用「響應」的值。它的工作原理,但是當路徑沒有這個孩子,它把我這個錯誤:
AngularJs過濾函數返回值的錯誤

firebase.js:283 Uncaught TypeError: Cannot read property '$value' of 
    firebase.js:276 FIREBASE WARNING: Exception was thrown by user callback. 
    TypeError: Cannot read property '$value' of undefined 

我用火力地堡-UTIL和Angularfire這樣的:

var ref = firebase.database().ref(); 

    var nc = new firebase.util.NormalizedCollection(
    ref.child('accounts/' + $localStorage.accountId + '/demandes'), 
    [ref.child('demandes'), 'widget2']).select('widget2.duree', 'widget2.derniere_modification', 'widget2.reponses', 'widget2.exp', 'widget2.ajout_le', 'widget2.localisation'). 
    filter(function(data, key, priority) { 
     return data.reponses.$value !== null; // This cause problems ! 
    }).ref(); 
    $scope.items = $firebaseArray(nc); 

我該怎麼辦以除return data.reponses.$value !== null;以外的適當方式進行測試?謝謝

+2

爲什麼不檢查孩子的存在並返回(data.responses && data.responses。$ value!== null)? – mhodges

回答

2

這聽起來像data.responsesundefined所以你可以檢查$value這樣的:

.filter(function (data, key, priority) { 
    return data.responses && data.responses.$value !== null; 
}).ref(); 

這可以確保有上data一個responses場你探查,以$value之前。

+0

第二種解決方案仍然使我回到同樣的錯誤,但第一個解決方案是做這項工作,謝謝你的回答@Zach –

+0

在刪除第二個代碼部分之前,我無法贊成這個答案。你的第一個代碼塊是我在評論中提出的建議,應該可以正常工作。但是,在第二個示例中,返回bool &&字符串通常會產生不直觀的結果。有關邏輯運算符的文檔,請訪問https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators – mhodges