如何使用 AngularFire 对对象应用部分更新 [英] How to apply a partial update to an object using AngularFire

查看:23
本文介绍了如何使用 AngularFire 对对象应用部分更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angularfire 0.8 中的 $save() 让我很困惑.

The $save() in Angularfire 0.8 is confusing me.

这是一个最小的例子 - 来自我的controllers.js 文件的片段:

Here's a minimal example - a snippet from my controllers.js file:

    .controller('LandingPageController', ['$scope','$firebase', function($scope,$firebase) {
        $scope.addNode = function() {
            var FB = new Firebase('https://protodb.firebaseio.com/testrecords/');
            var fbr = $firebase(FB);
            fbr.$set(1,{firstname: 'James'});
        }
        $scope.addAttribute = function() {
            var FB = new Firebase('https://protodb.firebaseio.com/testrecords/1');
            var fbr = $firebase(FB).$asObject();
            fbr.lastname = "Bond";
            fbr.$save();
        }
        }])

addNode() 被调用时,果然,在我的 firebase 中创建了一个节点:

When addNode() is called, sure enough, a node is created in my firebase:

但是当 addAttribute() 被调用时,整个记录被替换,而不是我所期望的,即要添加的姓氏"属性.

But when addAttribute() is called, the entire record is replaced, rather than what I expected, which was for the 'lastname' attribute to be added.

毫无疑问,我误解了文档.有人可以帮忙吗?

I've no doubt misunderstood the docs. Can anyone help?

更新:

好的,我需要等到对象被加载.在将 addAttribute 更改为:

OK, I needed to wait until the object was loaded. It works now, after changing addAttribute to:

    $scope.addAttribute = function() {
          var FB = new Firebase('https://protodb.firebaseio.com/testrecords/1');
          var fbr = $firebase(FB).$asObject();
          fbr.$loaded().then(function() {
              fbr.lastname = "Bond";
              fbr.$save();
          });
    }

推荐答案

正如你已经发现的那样:

As you found out yourself already:

  1. FirebaseObject(由 $asObject() 返回)没有 $update 方法.
  2. 当您在 FirebaseObject 完全加载之前调用 $save() 时,您最终可能会删除其他属性
  1. a FirebaseObject (as returned by $asObject()) does not have a $update method.
  2. when you call $save() on a FirebaseObject before it is completely loaded, you may end up deleting other properties

要修补现有数据,您可以:

To patch existing data you can:

  1. 要么等待整个对象被加载(就像你在更新问题时所做的那样)
  2. 或者直接调用$firebase.$update

$firebase(FB).$update({ lastname: "Bond" });

最后一种方法的优点是您不会下拉整个对象,只更新单个属性.请注意,这在大多数情况下可能是过早优化,但仍然......

This last approach has the advantage that you don't pull down the entire object, only to update a single property. Note that this is probably premature optimization in most cases, but still...

这篇关于如何使用 AngularFire 对对象应用部分更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆