如何在angularfire2中获取列表节点数?

时间:2017-03-15 16:11:58

标签: list count angularfire2

在firebase中有一个列表,

List
  key1
    item
  key2
    item
  key3
    item

我需要获取列表密钥计数,在上面的情况下= 3表示此列表,

我尝试了计数器属性但什么都没有

任何想法?

1 个答案:

答案 0 :(得分:0)

最基本的Angular 2方法是迭代键并在执行时递增计数器。

this.af.database.list(`list`)
.subscribe(keys => {
    keys.forEach(key => this.counter = this.counter + 1)
})

对此方法的有效反对意见是,在迭代所有这些键时,可以获取他们孩子的所有数据。 Firebase的shallow query uri参数允许您在不加载子项数据的情况下迭代键。要在Angular 2中执行此操作,您必须使用Http模块。这是一个粗略的近似值。

import { Http, Response } from '@angular/http';

constructor(private af: AngularFire, private http: Http) { }

countKeys() {
    this.http.get('https://your-database.firebaseio.com/keys.json?shallow=true')
    .subscribe(response => {
        Object.keys(response.json()).forEach(key => this.counter = this.counter + 1))
    }
}