如何将Firebase中的节点(对象)复制到另一个节点?
我在Firebase中有一个名为Events的节点。它由子对象组成,如:address
,description
,longitude
,latitude
。在用户删除事件节点之前,我想将其复制到同一个数据库中,并将其复制到名为eventsDeleted
的节点中。如何将Firebase中的节点(对象)复制到另一个节点?
这是删除节点的代码:
removeEvent(eventId, groupId) {
return new Promise((resolve, reject)=> {
this.eventRef.child(groupId).child(eventId).remove();
resolve();
});
}
这是创建的节点处的代码:
addEvent(data:any) {
console.log('Form data', data.group);
let localEventRef = firebase.database().ref('events').child(data.group.split(',')[1]);
let storageRef = firebase.storage().ref();
let file = data.image;
let uploadTask = storageRef.child('eventImages/' + UuidGenerator.generateUUID()).put(file);
uploadTask.on('state_changed', function (snapshot) {
}, function (error) {
// Handle unsuccessful uploads
console.error(error);
}, function() {
// Handle successful uploads on complete
let downloadURL = uploadTask.snapshot.downloadURL;
let keyOfNewEvent = localEventRef.push(
new Event(
null,
firebase.app().auth().currentUser.uid,
data.description,
data.location.address,
0
)
).key;
localEventRef.child(keyOfNewEvent).update({eventId: keyOfNewEvent});
});
}
没关系的代码上传的图像。我只需要一种方法来复制整个节点,然后将其粘贴到数据库的某个位置。提前致谢。
当用户单击删除时,请确保获取要删除的对象,如果要查询数据库中的该对象,则可以使用.once
来检索对象,否则您可以直接跳转到removeEvent
函数。
localEventRef.child(keyOfEvent).once("value", function(snapshot) {
//one data is returned, you can then call the removeEvent fn
let eventToBeRemoved = snapshot.val();
//assuming you have the eventid, groupid then.
removeEvent(eventId, groupId, eventToBeRemoved);
});
removeEvent(eventId, groupId, eventObjectToBeRemoved) {
//firebase 3.x comes with a promise method
firebase.database().ref('eventsDeleted/' + groupId + '/' + eventId)
.set({...eventObjectToBeRemoved})
.then(function() {
eventRef.child(groupId).child(eventId).remove();//you can now remove
})
.catch(function (error) {
console.error("error occured trying to add to deletedEvents", error);
});
});
}
一个新的项目,我不能执行这个代码,因为它,我很抱歉。我能够将代码的前三行放入removeEvent()函数中。我跑了,我可以像以前一样删除事件,但它没有在数据库上创建一个名为“eventsDeleted”的节点,并且数据正如我所希望的那样。我快到了,只是错过了一些东西。你能否提供进一步的帮助? – kuhle
哦,我希望你没有在'.set'上添加这些'..... eventObjectToBeRemoved',因为它只是一个例子吗?它的意思是像一个对象'{event:“”,id:“”}'...... –
非常感谢您的答复。我可以在set()中使用eventRef.child(groupId).child(eventId)吗?或者它必须是{event:“”,id:“”}? – kuhle
使用[angular.copy()](https://docs.angularjs.org/api/ng/function/angular.copy),并使用它创建 – charlietfl