如何绕过唯一 ID 获取 Firebase 中 snapshot.val() 的子属性

How to bypass a unique ID get the child property of a snapshot.val() in Firebase

本文关键字:val 属性 snapshot 唯一 何绕过 ID 获取 Firebase      更新时间:2023-09-26

我正在尝试查询Firebase数据库中的产品列表,当我查询该列表时,我想检索该产品的网址。

我已经能够查询产品列表。当我使用以下方法时:

$scope.filterForResult = function(userResponse){
    this.query = cleatsRef
    .orderByChild('filter')
    .startAt(userResponse.color+"_"+userResponse.sex+"_"+userResponse.studs+"_"+userResponse.upper+"_"+userResponse.price)
    .endAt(userResponse.color+"_"+userResponse.sex+"_"+userResponse.studs+"_"+userResponse.upper+"_"+userResponse.price);
    this.result = this.query.on('value', function(snapshot){
    return resultProduct = console.log(snapshot.val());
   });
};

以及当我使用以下用户响应时:颜色="黑色",性别="男性",螺柱="坚实的地面",上部="合成",价格="50",我收到正确的产品,作为一个对象:

"cleats":{    
  "adidas ACE 15,4 FG - Core Black - Matte Silver - White":{
    "brand":"adidas",
    "color":"black",
    "filter":"black_male_firm ground_synthetic_50",
    "price":50,
    "sex":"male",
    "stud":"firm ground",
    "upper":"synthetic",
    "url":"http://www.prodirectsoccer.com/US/products/adidas-ACE-154-FG-Mens-Soccer-Shoes-Firm-Ground-Core-Black-Matte-Silver-White-118537.aspx?"},"adidas ACE 15,4 FxG - Core Black - Silver Metallic - Solar Yellow":{"brand":"adidas","color":"black","price":50,"sex":"male","stud":"firm ground","upper":"synthetic","url":"http://www.prodirectsoccer.com/US/products/adidas-ACE-154-FxG-Soccer-Cleats-All-Ground-Core-Black-Silver-Metallic-Solar-Yellow-108740.aspx?"
  }
}

但是,我要做的下一步是检索产品的网址。如何绕过唯一 ID adidas ACE 15,4 FG - 核心黑色 - 哑光银 - 白色,以便访问 Firebase 中的网址属性?

这里有两件事。

查询返回子节点列表

每当您执行 Firebase 查询时,该值将始终是子项列表。即使只有一个结果,它仍然会在一个列表中。

因此,您需要在代码中处理它。

var filter = userResponse.color+"_"+userResponse.sex+"_"+userResponse.studs+"_"+userResponse.upper+"_"+userResponse.price;
this.query = cleatsRef
    .orderByChild('filter')
    .startAt(filter)
    .endAt(filter);
this.result = this.query.on('value', function(snapshot){
    snapshot.forEach(function(child) {
        console.log(child.val());
    });
});

无法返回仍在加载的数据

第二个问题是您正在尝试返回仍在加载的数据。这是不可能的,您也不能等到它被加载(您的用户不会欣赏这一点)。

若要更好地了解代码流,请添加以下日志语句:

console.log('before query');
this.result = this.query.on('value', function(snapshot){
    console.log('in query callback');
    snapshot.forEach(function(child) {
        console.log(child.val());
    });
});
console.log('after query');

您将看到输出为:

查询前

查询后

在查询回调中

这可能不是你所期望的。这种排序的原因是on()只*开始**加载数据。这可能需要一些时间,因此浏览器在 query.on(... 语句之后继续执行代码。然后,一旦结果可用,它就会调用您的回调函数。

解决方案可以是很多事情。但是由于您使用的是AngularFire,因此最有可能:

$scope.result = $firebaseArray(query)

然后在您的 HTML 中:

<div ng-repeat='child in result'>