How to apply a partial update to an object using AngularFire

爱⌒轻易说出口 提交于 2019-12-10 22:02:32

问题


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

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();
        }
        }])

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

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?

Update:

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();
          });
    }

回答1:


As you found out yourself already:

  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. Either wait for the entire object to be loaded (as you did in your update to the question)
  2. Or call $firebase.$update directly
$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...



来源:https://stackoverflow.com/questions/26035526/how-to-apply-a-partial-update-to-an-object-using-angularfire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!