【问题标题】:Firebase: Push to list embedded in an object with AngularFire2Firebase:使用 AngularFire2 推送嵌入到对象中的列表
【发布时间】:2017-05-14 15:48:13
【问题描述】:

我试图弄清楚如何使用 AngularFire2 将值附加到 Firebase 对象中的列表。用例是创建一个简单的记分板,每次更改时都会通过将以下Score 对象推送到列表来保存分数:

{
    points: [15, 11],
    sets: [2, 1],
    timestamp: new Date()
}

数据库中的Scoreboard 对象如下所示:

{
    event: 'Volleybal',
    home: 'Londen',
    away: 'Manchester',
    scores: [Score]
}

scores 数组是 Score 对象的数组,如上所述。我需要能够执行两项任务:

  1. 在 Firebase 数据库中查询 Scoreboard 列表以获得正确的事件(假设事件是唯一的)。
  2. 每次得分发生变化时,通过推送新的 Score 对象来更新 scores 数组。

这是正确的架构设计吗?如何使用 AngularFire2 执行这些任务?

【问题讨论】:

    标签: angular firebase firebase-realtime-database angularfire2


    【解决方案1】:

    看起来上面的架构可以涵盖您的用例。我建议 Scoreboard 对象的 scores 属性在您的代码中处理(并存储)为对象与数组。

    假设 event 属性对于所有 Scoreboard 对象都是唯一的,您可以使用以下内容从 Firebase 中检索它。

    const event = 'Volleyball';
    
    const scoreboards = af.database.list('scoreboards', {
      query: {
        orderByChild: 'event',
        equalTo: 'large' 
      }
    });
    

    但是,如果您在对象内有一个唯一键,则可能值得考虑将该键用于 Scoreboard 对象本身,因此记分牌资源如下所示

    {
        'Volleyball': {
            home: 'London',
            away: 'Manchester',
            scores: {}
        },
        'Football': {
            home: 'London',
            away: 'Manchester',
            scores: {}
        },
        ...
    }
    

    这样做将允许您检索/更新此对象,如下所示。

    // Get Scoreboard
    const event = 'Volleyball';
    const scoreboard = af.database.object('scoreboards/' + event);
    
    // Add a new score to the scores property of Scoreboard
    af.database.list('/scoreboards/' + event + '/scores').push({
      points: [15, 11],
      sets: [2, 1],
      timestamp: new Date()
    });
    

    值得注意的是,Firebase 实际上并不存储数组;如果你向 Firebase 展示一个数组,它会将它变成一个对象,键是数组的索引。 https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html

    根据下面的评论编辑答案 要显示最新存储的值,您可以使用类似下面的方法获取该值。

    const event = 'Volleyball';
    const scoreboard = af.database.list('/scoreboards/' + event + '/scores', {
      query: {
        orderByChild: 'timestamp',
        limitToLast: 1
      }
    });
    
    scoreboard.subscribe(list => {
       list.forEach(score => {
           // Can access the values of the Score object here
           console.log(score.points);
       });
    });
    

    【讨论】:

    • 感谢您的回复,这行得通。如何在我的角度模板中显示最新(及时)存储的值?
    • 已根据您的评论更新了我的答案,一旦您获得了可以在 Angular2 模板中正常使用它们的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2017-07-21
    • 2023-03-24
    • 2019-07-13
    相关资源
    最近更新 更多