【发布时间】:2017-07-18 18:43:22
【问题描述】:
我在下面有以下 Firebase 数据结构:
-posts
-postKey1
+commentKey1
+commentKey2
+commentKey3
在给定帖子密钥的情况下,我需要获取特定帖子的 cmets 数量。所以上面的数据应该为 postKey1 返回 3。
【问题讨论】:
标签: javascript ionic2 angularfire2
我在下面有以下 Firebase 数据结构:
-posts
-postKey1
+commentKey1
+commentKey2
+commentKey3
在给定帖子密钥的情况下,我需要获取特定帖子的 cmets 数量。所以上面的数据应该为 postKey1 返回 3。
【问题讨论】:
标签: javascript ionic2 angularfire2
据我所知,如果不下载您要计数的数据,就无法进行计数。
相反,您可以使用 AngularFire2 检索postKey1 下的所有数据,然后可以计算检索到的帖子。或者,如果您愿意付出努力,您可以使用 REST API,指定 shallow parameter 以仅检索 postKey1 下的键 - 然后您可以数数。
【讨论】:
numChildren。但是,如果我必须在所有实体/表中进行计数,这将成为一项重复性任务。例如,用户数、帖子数、投票数等。我认为 angularfire2 api 需要一个等效的 shallow 参数,它在 REST API 中可用
计算 cmets 数量的方法在 html 文件中的循环内调用。
...
<label>{{getCommentCount(post.$key)}} </label>
...
这是对我有用的实现。 numChildren() 方法成功了。另外我认为preserveSnapshot 似乎消除了我遇到的错误(例如无限调用/获取导致浏览器资源不足错误)。
getCommentCount(postKey: string) : number{
let commentCount = 0;
let url = `/posts/${postKey}`;
const posts = this.af.database.object(url, { preserveSnapshot: true });
posts.subscribe(snapshot => {
commentCount = snapshot.numChildren();
});
return commentCount;
}
【讨论】:
numChildren 获取计数将涉及从服务器检索该快照的所有数据。此外,订阅永远不会取消订阅,因此 AngularFire2 object 及其内部 Firebase ref 将在您的应用程序的生命周期中存在。通过从模板中调用getCommentCount,该函数将在每次更改检测时被调用。