0
votes

i'm trying to create a post-comment relationship​​ where the a user can write a post and others users can comment on the post.

I can show the posts but when in trying to do the join for displaying the comments that belongs to the post i cant.. below is my db schema

firebase db

i was thinking that first i need to get the key from the posts node and then move to comments and somehow get the comments of each post.. and use it in *ngfor inside the ngfor of the post?

i was trying something like

findAllComments(){

   this.db.list('posts', { preserveSnapshot: true})

    .subscribe(snapshots=>{
        snapshots.forEach(snapshot => {
          return this.db.list(`comments/${snapshot.key}`)
        });

    });
}

but this returns void of course:

When I console.log:

findAllComments(){

   this.db.list('/posts', { preserveSnapshot: true})

    .subscribe(snapshots=>{
        snapshots.forEach(snapshot => {
            const kapa = this.db.list(`comments/${snapshot.key}`).do(console.log)
            kapa.subscribe();
        });
    });
 }

I get in console this

console.log

I'm not sure if my thinking on this is right.

I'm confused because I am new in angular and firebase.

2

2 Answers

1
votes

You aren't returning a subset of posts (you're querying on all posts) so there's no need to have a join of any sort here. You can just query for all comments:

findAllComments(){
  // {preserveSnapshot: true} is deprecated
  return this.db.list('/comments').snapshotChanges(); 
}

Assuming you actually want to retrieve a subset of comments (not what your example depicts), you could do something like this:

this.replies = db.list('AngularFire/joins/messages').snapshotChanges().map(snapshots => {
  console.log('snapshots', snapshots);
  return snapshots.map(ss => {
    return db.list(`AngularFire/joins/replies/${ss.key}`).valueChanges();
  });
});

There is a complete working example of the latter here.

0
votes

I guess in the first part, you are not subscribing to the comments list. As there is no subscription to the comments, the request to the get the list of comments from firebase will not be fired and hence you don't see any comments.

In the second part, as you are subscribing to the comments list, you are seeing them.

In cases like these, where you want to fetch something based on a previous request, you could use switch/concat/merge Maps. Hope this helps