问题
How does angularfire .$save() compare to firebase .push()? I know push() will generate a unique key when data is stored, but I can't recreate the behavior using angularfire. Is there a way or should I be using .push() and if so, in what case would you use $save()?
Here is one sample I have using $save()...
var fb = new Firebase(FIREBASE_URI).child('Test');
var article = $firebaseObject(fb);
article.Foo = "bar";
article.$save().then(function(fb) {
console.log(fb.key() === article.$id); // true
}, function(error) {
console.log("Error:", error);
});
And another using .push()...
var article = new Firebase(FIREBASE_URI).child('Articles');
article.push({
title: $scope.article.title,
post: $scope.article.post
}, function(error) {
if (error) {
console.log("Error:", error);
}
});
What are the Pros/Cons and use cases for both?
回答1:
How push/$add and set/$save relate
AngularFire's $save()
method is implemented using Firebase's set()
method. Both save data to an existing/known location.
Firebase's push()
operation corresponds to AngularFire's $add()
method. Both will generate a new unique child key, which means you can use them to add new data at a location that is guaranteed to not conflict with any existing data.
When to use push and when to use set
While the above is a hard truth, this bit is more subjective. So don't blindly copy it, but figure out how it applies to your situation.
Typically you should be using set()
/$save()
if you either have an object that already exists in the database or if you are working with objects that have a natural key.
If the items don't have a natural key or you want them to be sorted "chronologically", you'll typically use push()
/$add()
to generate a key for you. This will ensure that the items are stored under a unique key and that newer items show up later in the list.
So if you're working with users, you'll typically store then under their uid
using something like ref.child('users').child(user.uid).set(user)
. On the other hand, if you're adding chat message to a chat room, you'll use something like ref.child('chat').push({ name: 'Adam Youngers', 'Firebase push() vs Angularfire $save()' })
.
来源:https://stackoverflow.com/questions/35954662/firebase-push-vs-angularfire-save