skip to Main Content

I have a firebase document with user data which contains ans array of project ids

I thought with this I could get every single id at once in the console log. But instead in every passthrough it logs all containing ids . Where am I mistaken?

const usersDocRef: AngularFirestoreDocument<any> = this.userCollectionRef.doc(this.userId);

 usersDocRef.snapshotChanges().pipe(switchMap((ref) => {
      const usersProjectIds = ref.payload.data().projects;
      return from(usersProjectIds); 
      
    })).subscribe((id) => {
      console.log(id);
      
    })

2

Answers


  1. Chosen as BEST ANSWER

    I just found out that the problem is in the snapshotChanges()-method.

    In the metadata of the payload the 'haspendingWrites'-property seems to change on every passthrough which causes a new emit for the snapshotChanges:

    https://stackoverflow.com/questions/66608321/snapshotchanges-emits-twice-even-when-the-document-hasnt-changed

    Now Iworked around with the get()-method. I am not very happy with that, because I expect a more reactive app behavior with the snapshotChange.

    But owed to my few experience with Angular and RxJS I just keep going with it.

    usersDocRef.get()
    .pipe(map((ref) => ref.data().projects))
    .subscribe((ids) => {
      console.log(ids);
    })
    

    Thank you very much for everyone that has tried to help me.


  2. You can do 2 things, the first one is to use instead of from another operator called of that does exacly what you want, but i raccomand you to use a map instad of switchMap like the following example, because in this case there is no need to recreate an observable. Just use what you get from the response and do a map.

    usersDocRef.snapshotChanges()
    .pipe(map((ref) => ref.payload.data().projects))
    .subscribe((ids) => {
      console.log(ids);
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search