angular - Firebase - 我如何在 Firebase 实时数据库中更新一个对象
如何更新现有对象。
我在更新 Firebase 实时数据库中的对象时遇到了麻烦。
有人知道怎么做这个吗?
我正在使用:Angular 和 TypeScript。
这是我当前的 TypeScript 代码:
updateProfile = (profile): any => {
return new Promise((resolve, reject) => {
var refProfile = new Firebase("https://poolcover.firebaseio.com/profiles");
refProfile.update(profile, function(error) {
if (error) {
console.log('Synchronization failed');
resolve(false);
} else {
console.log('Synchronization succeeded');
resolve(true);
}
});
})
}
答案#1
你需要找到个人资料的 key。在存储用户数据时,你应该使用 uid 作为 key,而不是使用 .push() 生成的 id。
另外,不要使用完成回调,改用监听器。
已完成的回调会等待服务器响应,而监听器首先在本地触发。所以监听器回调更快。
constructor() {
this.profileRef = new Firebase("<my-firebase-app>/profiles");
var currentUser = this.profileRef.getAuth(); // if authenticated
this.userRef = refProfile.child(currentUser.uid);
userRef.on('value', (snap) => {
console.log('Profile updated');
console.log(snap.val()); // update profile info
});
}
updateProfile(profile) {
this.userRef.update(profile);
}
