angularfire icon indicating copy to clipboard operation
angularfire copied to clipboard

forEach works with snapshotChanges(), but not .map, even though the documentation says it should.

Open Metsuryu opened this issue 9 years ago • 21 comments

Version info

Angular: 4.2.4

Firebase: "firebase": "^4.5.0"

AngularFire: "angularfire2": "^5.0.0-rc.1"

Other (e.g. Ionic/Cordova, Node, browser, operating system): AngularCLI Project, Windows 7

How to reproduce these conditions


allUsers: AngularFirestoreCollection<any>;
users: Observable<any[]>;

//then in constructor:
this.allUsers = db.collection("users");
this.users = this.allUsers.snapshotChanges();

// This works:
this.users.forEach( user => {
  user.forEach( userData =>{
    let data = userData.payload.doc.data();
    let id = userData.payload.doc.id;
    console.log( "ID: ", id, " Data: " , data );
    });
});
// This doesn't work, when it should:
this.users.map(actions => {
  return actions.map(a => {
    const data = a.payload.doc.data();
    const id = a.payload.doc.id;
    console.log( "ID: ", id, " Data: " , data );
    return { id, data };
    });
});

Debug output

** Errors in the JavaScript console ** None.

Expected behavior

.map() should work.

Actual behavior

.map() doesn't work.

Metsuryu avatar Oct 05 '17 06:10 Metsuryu

After upgrading to ^5.0.0-rc.9 it finally works like this:

this.tasksCollection.snapshotChanges().pipe(
        map(
            changes => { return changes.map(a => {
            const data = a.payload.doc.data() as Task;
            data.id = a.payload.doc.id;
            return data;
          });
          }
        )).subscribe();

It works important use snapshotChanges instead of valueChanges, otherwise will not work

federicorojas11 avatar May 03 '22 12:05 federicorojas11