Copy a $firebaseObject and save it to a different location

后端 未结 2 408
不思量自难忘°
不思量自难忘° 2021-01-28 05:23

In my application i\'m getting an object from my firebase using $firebaseObject. The use has two options with this object, change it and save the changes in the object or change

相关标签:
2条回答
  • 2021-01-28 05:34

    You can use $value field of $firebaseObject.

    for instance:

    var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
    var FBObj1 = $firebaseObject(ref.child('child'));
    ref.child('newChild').set(FBObj1.$value);
    

    EDIT:

    Since this only works for primitives, you can try something like this:

    function getObject(obj) {
        var newObj = {};
        for (var key in obj) {
           if (key.indexOf('$') < 0 && obj.hasOwnProperty(key)) {
              newObj[key] = obj[key];
           };
        }
        return newObj;
    }
    

    and use getObject(FBObj1) insetad of FBObj1.$value

    0 讨论(0)
  • 2021-01-28 05:38

    Incredibly useful answer. Adding my own solution which is just an expansion on Frane and using Angularfire 2.3:

    End result:

    • Bind first object to DOM When saving first object, save same object to another node using the same key to allow for future cross-reference In theory, you can also insert fields if needed before saving to node #2

    The html:

    <a href="#" editable-text="data.field1" onaftersave="saveData()">
    {{ data.field1 || "empty"  }}
    </a>
    
    <a href="#" editable-text="data.field2" onaftersave="saveData()">
    {{ data.field2 || "empty"  }}
    </a>
    

    In the controller:

    var ref = firebase.database().ref().child(entries);
    var obj = $firebaseObject(ref);
    obj.$bindTo($scope, "data");
    
    
    function saveData(){
        $scope.data.$save().then(function() {
            var newObject = getObject($scope.data);
            // In theory, add other field here
            var ref2 = firebase.database().ref().child(otherNode).child($scope.data.$id);
            ref2.update(newObject);
        }).catch(function(error) {
            console.log('Error ' + error.message);
        });
    }
    
    function getObject(obj) {
        var newObj = {};
        for (var key in obj) {
            if (key.indexOf('$') < 0 && obj.hasOwnProperty(key)) {
                newObj[key] = obj[key];
            };
        }
        return newObj;
    }
    
    0 讨论(0)
提交回复
热议问题