问题
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 it and save it as a new version.
My problem is getting the second option to work. For the first i can simply use $save() and it works perfectly but so far i haven't been able to make a copy of the object and save it in a different location in my firebase.
So far i have tried:
- Saving the actual object in a different location (Error: Firebase.push failed: first argument contains an invalid key ($$conf) in property)
- Usin angular.copy($firebaseObject) to make a copy of the object (Error: 'length' getter called on an object that does not implement interface Storage.)
- Using $value of the $firebaseObject (Gives undefined because my object isn't a primitive, see $value documentation)
- Making a seperate object in javascript and manually copy all the values from the $firebaseObject
The first 3 options failed (error codes are shown with the options) and the last option works but is not really an option because the object can have different fields.
Does anyone know a solution for this problem?
回答1:
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
回答2:
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;
}
来源:https://stackoverflow.com/questions/35508291/copy-a-firebaseobject-and-save-it-to-a-different-location