sheeni
sheeni

Reputation: 407

Angularfire2 Update a Record

i'm pretty new to angular and I'm in the process of building a small web app.

I've managed to setup angularfire 2 and successfully managed to create a new list entry using Push().

Let's say my list (users) consists user email and first name. only the email is added via the Push method and i want to update that record by adding first name.

I referred to the Angularfire2 documentation and managed to get this far:

 usrEmail: string;
 usrData: AngularFireList<any>;
 usr: Observable<any>;


  constructor( private authService: AuthService, private afd: AngularFireDatabase) {


    this.usrData = this.afd.list('/users')
    // now get the current user
    this.usr = this.usrData.snapshotChanges().map(changes => {
      return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
     });

  }

I'm not sure how i should filter the list by the usrEmail and obtain the key to update the record.

Any help pointing me at the right direction is much appreciated.

Upvotes: 1

Views: 2127

Answers (1)

sketchthat
sketchthat

Reputation: 2688

The query you've used gets all /users not just the single user with the matching email address.

I've assumed that you have access to the email address and it's assigned to a variable userEmailAddress.

this.usr = this.afd.list('/users', ref => ref
  .orderByChild('usrEmail')
  .equalTo(userEmailAddress)
)
.snapshotChanges()
.map(changes => {
  return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
})
.first()
.subscribe(snapshots => {
  snapshots.forEach(snapshot => {
    console.log('Snapshot Key: ', snapshot.key);
    console.log('Snapshot Payload: ', snapshot.val());
  });
});

The output of the snapshot.key will be the key you're trying to fetch.

However in your scenario there would be a better way to store the customers email address. You can create a path containing the user-id within the database, such as;

I'll assume you have access to the uid via the the authService. this.authService.uid

this.afd.object(`/users/${this.authService.uid}`).update({
  email: userEmailAddress
});

The uid of the user will never change and it's unique to that user, so you can create database paths with it for easy access.

Upvotes: 1

Related Questions