AngularFire Accessing child element methods

跟風遠走 提交于 2019-12-04 16:22:46
Frank van Puffelen

Firebase will load the data from the server only once. After that your JavaScript code can construct as many refs on it as you need, without downloading the data again.

But post.comments.$asArray() will not work, since your post is a plain JavaScript object (and not a $firebase sync anymore).

Instead try:

var ref = new Firebase(FIREBASE_URL + "/posts/" + post_name);
var post = $firebase(ref).$asObject();
var comments = $firebase(ref.child("comments")).$asArray();

Consider an alternate data structure

But you may want to reconsider your data structure. Even though Firebase is a hierarchical data store, they recommend against building deeply nested hierarchies. See Avoid Building Nests on https://www.firebase.com/docs/web/guide/structuring-data.html

Because we can nest data up to 32 levels deep, it's tempting to think that this should be the default structure. However, when we fetch data for a node in Firebase, we also retrieve all of its child nodes. Therefore, in practice, it's best to keep things as flat as possible, just as one would structure SQL tables.

So in your case that could lead to having two top-level elements posts and comments.

root
  posts
    post1
    post2
  comments
    post1
      post1comment1
      post1comment2

And you can then simply load the post and its comments with:

var root= new Firebase(FIREBASE_URL);
var post = $firebase(root.child("posts").child(post_name)).$asObject();
var comments = $firebase(root.child("comments").child(post_name)).$asArray();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!