DauleDK
DauleDK

Reputation: 3453

Firebase: Update item in list binding using AngularFire2

According to the angularfire2 documentation the following can be done when you wan't to update a item in a list :

const items = af.database.list('/items');
// to get a key, check the Example app below
items.update('key-of-some-data', { size: newSize });

But is is possible to update an item in the list, without having to specify key:values for the object like this?

items.update('key-of-some-data', item);

In angularfire this is possible to do like this:

<li ng-repeat="item in list">
<input type="text" ng-model="item.title" ng-change="list.$save(item)" />
</li>

Thanks for taking your time to read this question :)

Upvotes: 2

Views: 4715

Answers (1)

cartant
cartant

Reputation: 58440

The implementation of update looks like this:

update(item: FirebaseOperation, value: Object): firebase.Promise<void> {
  return this._checkOperationCases(item, {
    stringCase: () => this.$ref.ref.child(<string>item).update(value),
    firebaseCase: () => (<firebase.database.Reference>item).update(value),
    snapshotCase: () => (<firebase.database.DataSnapshot>item).ref.update(value),
    unwrappedSnapshotCase: () => this.$ref.ref.child((<AFUnwrappedDataSnapshot>item).$key).update(value)
  });
}

So it's possible to call update in the following ways:

  • Using a string key and a value:

    const items = af.database.list('/items');
    items.update('key-of-some-data', { size: newSize });
    
  • Using a Firebase ref and a value:

    const items = af.database.list('/items');
    const ref = items.$ref.ref;
    items.update(ref.child('key-of-some-data'), { size: newSize });
    
  • Using a Firebase snapshot and a value:

    const items = af.database.list('/items', { preserveSnapshot: true });
    items.subscribe(list => {
      const snapshot = list[0];
      items.update(snapshot, { size: newSize });
    });
    
  • Using an unwrapped list item and a value:

    const items = af.database.list('/items');
    items.subscribe(list => {
      const item = list[0];
      items.update(item, { size: newSize });
    });
    

(The snippets above that call subscribe are only to illustrate that the snapshot and unwrapped items are the list observable's emitted values. Using subscribe like this to perform an update makes no sense.)

AngularFire2 is currently undergoing some refactoring and rearranging in preparation for a release candidate. If you have a use case for which none of the above options is suitable, now is the time to speak up. The discussion is here. However, for something this specific, you should create a new issue.

Upvotes: 7

Related Questions