2016-08-22 51 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