使用AngularFire2获取Firebase节点的孩子数量? [英] Get number of children for a Firebase node using AngularFire2?

查看:183
本文介绍了使用AngularFire2获取Firebase节点的孩子数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要统计Firebase中多个子树的子节点数,以便在视图中显示。对于上下文,我的应用程序正在统计用户在一个进程的不同阶段。

我的根节点(stage)有两个子树(stageOne,stageTwo)。每个子树都包含一个可变数量的子节点,我需要在视图中进行计数和显示。



数据库:

 阶段
| __stageOne
| | __user1
| | __user2
|
| __stageTwo
| __user3

组件:

  stageObject:FirebaseObjectObservable< any>; 

构造函数(public af:AngularFire){
this.stageObject = af.database.object('/ stages');



$ b $ p $查看(不显示)

 < h3>第1阶段计数= {{(stageObject | async)?. stages.stageOne.length}}< / h3> 
< h3>第2阶段计数= {{(stageObject | async)?. stages.stageTwo.length}}< / h3>

查看(应该是这样):

 第1阶段计数= 2 
第2阶段计数= 1


class =lang-ts prettyprint-override> this.http.get('https://your-app-name.firebaseio.com/stages/stageOne.json?shallow=true')
.map(response => response.json())
.subscribe(items => Object.keys(items).length)

使用 shallow = true 节点。

$ hr

如果要加载所有这些元素,可以使用 list / code>:


$ b

  this.stageOneObject = af.database.list('/阶段/ stageOne'); 

或将对象转换为数组:

  this.stageOneObject = Object.keys(this.stageObject.stageOne)
.map(key => this.stageObject.stageOne [key]) ;


I need to count the number of children nodes for multiple subtrees in Firebase to display in the view. For context, my app is counting users at different stages in a process.

My root node (stages) has two subtrees (stageOne, stageTwo). Each subtree contains a variable number of child nodes which I need to count and display in the view.

Database:

stages
|__stageOne
|  |__user1
|  |__user2
|
|__stageTwo
   |__user3

Component:

stageObject: FirebaseObjectObservable<any>;

constructor(public af: AngularFire){
    this.stageObject = af.database.object('/stages');
}

View (doesn't display)

<h3>Stage 1 Count = {{ (stageObject | async)?.stages.stageOne.length }}</h3>
<h3>Stage 2 Count = {{ (stageObject | async)?.stages.stageTwo.length }}</h3>

View (how it should look):

Stage 1 Count = 2
Stage 2 Count = 1

解决方案

You can't get count with AngularFire2 (without loading all items), but you can use REST API:

this.http.get('https://your-app-name.firebaseio.com/stages/stageOne.json?shallow=true')
  .map(response => response.json())
  .subscribe(items => Object.keys(items).length)

Using shallow=true will return just keys for all children for 'selected' node.


If you want to load all of them, you can use list():

this.stageOneObject = af.database.list('/stages/stageOne');

or transform object to array:

this.stageOneObject = Object.keys(this.stageObject.stageOne)
                            .map(key => this.stageObject.stageOne[key]);

这篇关于使用AngularFire2获取Firebase节点的孩子数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆