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

查看:18
本文介绍了firebase $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 方法,因此将数据推送给 child 时将使用新的随机 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" }
   ]}
}

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

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 方法的任何空值都会删除原来存在的任何数据.

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

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

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