【问题标题】:How to read and update based on item $id in Firebase?如何根据 Firebase 中的项目 $id 读取和更新?
【发布时间】:2017-02-28 06:41:12
【问题描述】:

我不知道如何使用基于 id 的 Firebase 进行读取和更新。在这种情况下,我有一个待办事项列表,我想根据其 $id 找到第一项,然后将 comple 更改为 true。

todos
  -Ke0JWl9xy5sZvT55hfE
       Complete:  false
       Created_at: 1488228401479
       Description: "123"
       Priority: "high"
  -Ke0Ms_LnsO-TSwQZLcZaddclose
  -Ke0MuWCLkX29XWYyPBM
  -Ke0MwKOrjpDm9rj6L28
  -Ke0NCmpM3_dTPtY9jVb

JS

(function() {
  function Todo($firebaseArray) {
    var ref = firebase.database().ref().child("todos");
    var todos = $firebaseArray(ref);

    Todo.todos = todos;
    Todo.updateToDo = function(todo){
      console.log(todos)

      console.log(todos[todo['$id']])
    };
    return Todo;
  }

  angular
    .module('blocitoff')
    .factory('Todo', ['$firebaseArray', Todo]);
})();

【问题讨论】:

    标签: angularjs firebase firebase-realtime-database angularfire


    【解决方案1】:

    我会采取更简单的方法:

    (function() {
      function Todo($firebaseArray) {
        var ref = firebase.database().ref().child("todos");
        var todos = $firebaseArray(ref);
    
        Todo.todos = todos;
        Todo.updateToDo = function(todo){
          ref.child(todo['$id']).update({ completed: true });
        };
        return Todo;
      }
    
      angular
        .module('blocitoff')
        .factory('Todo', ['$firebaseArray', Todo]);
    })();
    

    此处的 update() 调用使用 Firebase JavaScript SDK。但由于 AngularFire 是在此基础上构建的,它们无论如何都可以完美地互操作。

    【讨论】:

    • 谢谢!那行得通。这有点相关,那么如何根据$id 返回该对象?当我尝试使用console.log(ref.child(todo['$id'])); 时,它只返回U {u: Te, path: L, m: ee, Nc: false, then: undefined…}。我的目标是到达Description
    • 该代码只是设置了一个引用。它还没有检索到任何值。要了解如何在没有 AngularFire 的情况下从 JavaScript 访问数据库,我建议:firebase.google.com/docs/database/web/start
    猜你喜欢
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    相关资源
    最近更新 更多