【问题标题】:How to set the key name on an array in Angularfire如何在Angularfire中的数组上设置键名
【发布时间】:2015-06-10 06:04:02
【问题描述】:

我正在使用 Angularfire 创建数组,但无法设置键名。 Firebase 会自动给我一个神秘的密钥(例如 Jm9vLy8Lye-KS35KsmL),但我想自己将其设置为更有意义的东西。目前还不清楚我是如何在 Angularfire 中做到这一点的。我在 $firebaseArray 上使用 $add 方法:

var firebaseRef = new Firebase("https://firebase_location"); 
$scope.messages = $firebaseArray(firebaseRef);

$scope.messages.$add( 
  {
    FirstName: patient.FirstName, 
    LastName: patient.LastName
  }
).then(function(firebaseRef) {
  var id = firebaseRef.key();
});

数据存储良好,我可以在仪表板上看到它。但是, id 始终是一个神秘的 firebase 值。我希望能够自己将其设置为有意义的东西。在我的情况下,个别患者的 ID 将是有意义的......

有什么想法吗?

谢谢!

【问题讨论】:

    标签: angularjs firebase angularfire


    【解决方案1】:

    感谢您的回复。

    我发现子函数会做我需要的。我先指定孩子,然后设置。

    var patient_child = firebaseScreenRef.child(patient.PatientId); 
          patient_child.set(
            { 
                FirstName: patient.FirstName, 
                LastName: patient.LastName, 
            });
    

    【讨论】:

    • 这有帮助!我首先尝试同时使用 $firebaseObject 和 $firebaseArray,但只有 ref 有效——你必须直接使用 ref...
    • 我花了一些时间来理解这一点,但它确实有效。谢谢!
    【解决方案2】:

    将项目添加到 firebase 数组会使 firebase 为您定义一个唯一的 ID。如果这不是您想要的,我认为您可以尝试使用 $firebaseObject 获取“消息”对象,而不是仅使用 $firebaseArray 获取列表。然后您将能够在 js 中编辑您的对象,以便将您的项目添加到消息集合中。通过这种方式,您可以使用最适合您需求的 id。最后,你必须 $save() 你的整个对象。看这里:https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebaseobject

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      对于你的问题,我找到了解释。不需要使用firebaseObject,直接使用ref即可:

      var ref = new Firebase(FURL);
      
      createProfile: function(id ,user) {
      
        var profile = {`enter code here`
                      name: user.name,
                      email: user.email,
                      gravatar: get_gravatar(user.email, 40)
                  };
      
        var profileRef = $firebaseArray(ref.child('profile').child(id));
      
        return ref.child('profile').child(id).set(profile);
      },
      

      在代码中,我使用 ref 来引用我的 URL。使用 profileRef,我创建了一个子配置文件,并为该配置文件添加了 ID。之后,我直接使用 ref 为我想要的 id 设置值profile。你看,这很容易。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-17
        • 1970-01-01
        • 2011-04-11
        • 2021-06-19
        相关资源
        最近更新 更多