如果我重组数据以供使用,如何让 Firebase 自动更新它? [英] If I restructure data for use, how can I make Firebase automatically update it?
问题描述
如果我使用:
var ref = new Firebase("https://myURL.firebaseio.com/");
var sync = $firebase(ref);
var firebaseData= sync.$asObject();
firebaseData
将随着 https://myURL.firebaseio.com/
中的数据变化而变化.它们将保持同步.
firebaseData
will change as data from https://myURL.firebaseio.com/
changes. They will be in sync.
如果我重组数据,并将其定义为一些新变量 var newStructure
,我怎样才能让它与 https://myURL.firebaseio.com/
同步或 firebaseData
?
If I restructure data, and define it as some new variable var newStructure
, how can I get it to sync with https://myURL.firebaseio.com/
or firebaseData
?
有没有一种方法可以让我观察 firebaseData
中的变化并调用重组方法?
Is there a way I can watch for changes in firebaseData
and recall the restructuring method?
有没有办法知道 firebaseData
中具体发生了什么变化,并且只对 newStructure
进行相关更改?
Is there a way to know what specifically changed in firebaseData
and make only relevant changes to newStructure
?
有没有一种方法可以让 newStructure
直接与 Firebase 同步,尽管使用不同的结构解析数据?
Is there a way that newStructure
can sync directly with Firebase, albeit have data parsed with a different structure?
推荐答案
你的变量 firebaseData
代表你的 firebase 集合.
Your variable firebaseData
represents your firebase collection.
您对 firebaseData
所做的所有更改都将跨连接同步:
All changes you make to firebaseData
will be syncronized across connections:
var ref = new Firebase("https://myURL.firebaseio.com/");
var sync = $firebase(ref);
var firebaseData = sync.$asObject();
您可以查看是否对对象进行了任何更改:
You can watch to see if any changes have been made to the object:
firebaseData.$watch(function(event){
console.log("Change made to this firebase object");
// Then you can call a function which could restructure your data:
restructureData(firebaseData, event);
});
因此您的 restructureData
函数可能如下所示:
So your restructureData
function could look like this:
var restructureData = function(firebaseObj, event){
// This function updates firebase on every change to firebase
// But we don't want to update it again after running this function
if(event.key === "changesMadeToFirebase") return;
firebaseObj.changesMadeToFirebase += 1;
firebaseObj.$save().then(function(){
console.log("data restructured");
}, function(err){
console.log("There was an error:", err);
});
};
这允许您检查对 firebase 进行了多少更改,但对字段 "changesMadeToFirebase"
This allows you to check how many changes have been made to firebase, except for the changes to the field "changesMadeToFirebase"
虽然这是一个很小的例子,但您可以在这里找到更多:
Although this is a very small example, you will be able to find much more here:
https://www.firebase.com/docs/web/图书馆/angular/api.html
这篇关于如果我重组数据以供使用,如何让 Firebase 自动更新它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!