火力$ add().push().set() [英] firebase $add() .push() .set()

查看:104
本文介绍了火力$ add().push().set()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase和angularfire. 使用Firebase Api进行CRUD的方法有很多 实际上,我仍然不知道使用的具体区别是什么

I am using firebase, and angularfire. there are so many ways to do CRUD with the Firebase Api actually, I still don't get what is specific difference for using

  • $ add与$ firebaseArray
  • .push()方法
  • .set()方法

我认为它们在技术上是相同的,我更喜欢使用.set method()而不知道确切的原因,为什么要使用它.有没有特定的原因不使用它? $ firebaseArray到底做了什么?如果我们只能声明基本参考变量.

I think they are technically same, I prefer to use .set method() without knowing the exact reason, why I'd using that. is there any specific reason to not use it? what is exactly $firebaseArray did? if we could just declare basic reference variable.

在这种情况下:

var usersRef = Ref.child('users');

  $scope.createUser = function() {
    $scope.userRef.child($id).set({
       name: name
           });
      };

$scope.data = $firebaseArray(Ref.child('users'));

$scope.createUser = function() {
  $scope.data.child($id).$add({
    name: name
  });
 };

谢谢.

推荐答案

如果我在Firebase中具有以下数据树:

If I have the following data tree in Firebase:

{
  users:
   {
      key: { name:"bob" }
   }
}

当我执行$ add时,我将在树中创建一个新项目

When I do an $add, I will create a new item in the tree

$scope.data.child('users').$add({
    name: name
  });

由于$ add在Firebase中使用Push方法,因此在将数据推送到子级时将使用新的随机Key.

Since $add uses the Push method in Firebase, new random Key will be used when pushing data to the child.

{
  users:
   {[
      key: { name:"bob" },
      key2: { name:"name" }
   ]}
}

如果对同一个Users对象进行设置,则将覆盖已经存在的数据.因此,在您的示例中,无需指定键,您将覆盖整个用户对象.

If I do a set on the same Users object, I will overwrite the data that is already there. So, in your example, without specifying a key, you will overwrite the entire user object.

$scope.userRef.child('users').set({
       name: name
           });
      };

这将得到这些数据

{
  users:
   {
      name: "name"
   }
}

之所以会发生这种情况,是因为您传递给Set方法的任何null值都将删除原来存在的所有数据.

This happens because any null values you pass to the Set method will delete any data that was originally there.

将null传递给set()将删除指定位置的数据. https://www.firebase.com/docs/web/api/firebase/set.html

Passing null to set() will remove the data at the specified location. https://www.firebase.com/docs/web/api/firebase/set.html

这篇关于火力$ add().push().set()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆