Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 71531

How to make an Observable from a query in Firebase?

$
0
0

@nairdagui wrote:

This is my original code where the posts is only an array. My problem here is that it does not auto update on view when the data changes.

posts = [];
loadPosts() {
    this.user.getFollowedGroups().subscribe((result) => {
      this.groupsFollowed = result.following;
      this.postsCollection.ref.where('gid', 'in', this.groupsFollowed).get().then(res => {
          res.docs.forEach(doc => {
            let obj = doc.data();
            obj["id"] = doc.id;
            this.posts.push(obj);
          });
        });
    });
  }

So I am trying to save it on an observable instead. This is how I do it on other services which I dont use where query. I tried mixing it up and putting the query inside the queryFn,

followedPostsCollection: AngularFirestoreCollection<Post>;
posts: Observable<Post[]>;
loadPosts() {
    this.user.getFollowedGroups().subscribe((result) => {
      this.groupsFollowed = result.following;
      this.followedPostsCollection = this.afs.collection<Post>('announcements', ref => ref.where('gid', 'in', this.groupsFollowed));
      this.posts = this.followedPostsCollection.snapshotChanges().pipe(
        map(actions =>
          actions.map(a => {
            const data = a.payload.doc.data();
            const id = a.payload.doc.id;
            return { id, ...data };
          })
        )
      );
    });
  }

getPosts(): Observable<Post[]> {
    return this.posts;
  }

but this code gives me undefined posts when I subscribe with it. Where do I go wrong and how to make it work? Or should I just use .onSnapshot or .then like what I did on the first one but I cant seem to save it on an observable.

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 71531

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>