Firebase:使用 AngularFire2 更新列表绑定中的项目

Firebase: Update item in list binding using AngularFire2

根据 angularfire2 文档,当您不想更新列表中的项目时,可以执行以下操作:

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

但是是否可以更新列表中的项目,而不必像这样为对象指定 key:values?

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

angularfire 中可以这样做:

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

感谢您花时间阅读这个问题:)

update 的实现看起来像 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)
  });
}

所以可以通过以下方式调用update

  • 使用 string 键和值:

    const items = af.database.list('/items');
    items.update('key-of-some-data', { size: newSize });
    
  • 使用 Firebase 引用和值:

    const items = af.database.list('/items');
    const ref = items.$ref.ref;
    items.update(ref.child('key-of-some-data'), { size: newSize });
    
  • 使用 Firebase 快照和值:

    const items = af.database.list('/items', { preserveSnapshot: true });
    items.subscribe(list => {
      const snapshot = list[0];
      items.update(snapshot, { size: newSize });
    });
    
  • 使用展开的列表项和值:

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

(调用 subscribe 上面的代码片段只是为了说明快照和展开的项目是 list observable 的发射值。像这样使用 subscribe 来执行更新使得没有意义。)

AngularFire2 目前正在进行一些重构和重新安排,以准备发布候选版本。如果您有 none 以上选项适合的用例,现在是时候说出来了。讨论是here. However, for something this specific, you should create a new issue.