0

I try to get the user for each of my messages documents. We have :

users
    user_id => user_data
message
    msg_id => { message, user_id }

So I tried ( based on that answer ) :

getUserData(userId) {
  const docRef = this.afs.collection('/users').doc(userId);
  return docRef.ref.get();
}

getMsgs(topicId){
  return this.afs.collection('/topics_msgs/' + topicId + "/comments").snapshotChanges().map(actions => {
    return actions.map(a => {
      const commentData = a.payload.doc.data();
      this.getUserData(commentData.user_id).then(
        user => {
          return {user: user.data(), ...commentData};
        }
      );
    });
  });

}

and in component :

this.firebaseService.getMsgs(this.id).subscribe( msgs => {
  console.log(msgs);
  this.messages = msgs;
})

but of course it can't work - inner map doesn't return anything outside of the promise, so the component receives a list of undefined.

I'm a little stuck here about how to deal with this. Thanks ahead.

Jeremy Belolo
  • 4,319
  • 6
  • 44
  • 88

1 Answers1

1

Use higher order observables to transform your data into a type that suits your need. Regarding your problem (and from what I understand), you can do something like this:

    getUserData(userId): Observable<UserData> {
      const docRef = this.afs.collection('/users').doc(userId);
      return docRef.snapshotChanges().pipe(
          map(action => ({ ref: action.payload.ref, ...action.payload.data()}))
      );
    }

    getMsgs(topicId): Observable<CommentData[]>{
      return this.afs.collection('/topics_msgs/' + topicId + "/comments").snapshotChanges().pipe(
        mergeMap(actions => {
          const commentsDataObservableArray: Observable<CommentData>[] = actions.map(a => {
            const commentData = a.payload.doc.data();
            return this.getUserData(commentData.user_id).pipe(
              map(user => {
                return {user: user.data(), ...commentData};
              })
            );
          });
          return combineLatest(commentsDataObservableArray);
        })
      );
    }
Quentin Fonck
  • 1,286
  • 9
  • 14