如何在 Firebase 的 Angular-Fire 中使用 $save() 来更新对象属性值

How do I use $save() in Firebase' Angular-Fire to Update Object Property Values

本文关键字:save 更新 属性 对象 Firebase Angular-Fire      更新时间:2023-09-26

我有下面的代码:

var FBref = new Firebase('https://employees.firebaseio.com/');
var peopleObject = $firebaseArray(FBref);
var person = {  
            "name":"John",
            "age":"20",
            "phone":"123-123-123"
        };
peopleObject.$add(person);  

我使用上面的代码成功添加了员工的新记录。

我需要将 John 的电话号码更新为 111-111-111。但是下面的代码不起作用。

var person = {  
            "name":"John",
            "age":"20",
            "phone":"111-111-111" //New phone number
        };
peopleObject.$save(person);

有人建议

目前您正在尝试保存整个对象,这不起作用。

首先通过从数据库获取记录来检索旧记录,然后更新该记录。此后使用$save方法保存该对象。

//if update action is happening is similar session you can get unique by below code
var someRecordKey; 
peopleObject.$add(person).then(function(ref) { 
    //get record id of new person 
    someRecordKey = ref.key(); 
});
// get record by unique key
var person = peopleObject.$getRecord(someRecordKey);
// change a message and save it
item.phone = "111-111-111";
peopleObject.$save(person).then(function() {
    // data has been saved to our database
});